react狀態

 state注意事項:

  • 不能直接this.state = xx修改,必須用this.setState({xx : xx})
  • 因爲setState做了兩件事:1.修改狀態 2.重新render

this.setState原理:

this.setState({number:this.state.number+1})

//等價於:

Object.assign(this.state,{number:this.state.number+1})

在組件裏解決this指針的三種方法:

  • 使用bind this.fn.bind(this) 把fn方法裏面的this指針綁定爲組件實例
  • 使用匿名函數  <button onClick={()=>{this.xx();}}
  • 使用類的屬性(給類的實例增加一個屬性,而這個屬性裏的this綁定爲組件的實例)
import React from 'react';
import ReactDOM from 'react-dom';
class clock extends React.Component{
    constructor(props){
        super(props);
        //在構造函數裏,唯一可以給this.state賦初始值的地方
        this.state = {date:new Date().toLocaleTimeString()}
    }
    add(){
        console.log('add',this)
    }
    min=()=>{
        console.log('min',this)
    }
    //組件掛載完成後調用
    componentDidMount(){
        this.$timer = setInterval(()=>{
            this.setState({
                date:new Date().toLocaleTimeString()
            },1000)
        })
    }
    render(){
        return <div>時間:{this.state.date}
            <button onClick={()=>{this.add()}}>匿名函數改變this</button>
            <button onClick={this.min}>類的屬性改變this</button>
        </div>
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章