react之組件的生命周期

生命周期的方法

void constructor(props)

組件的構(gòu)造,我們可以再這里初始化數(shù)據(jù),調(diào)用一次

void componentWillMount()

組件將要渲染,調(diào)用一次,在render調(diào)用之前

ReactElement render()

這個(gè)是組件最重要的,必須實(shí)現(xiàn)的且必須包含返回值,一般我們?cè)谶@里返回我們的組件信息

void componentDidMount()

組件渲染完成 ,調(diào)用一次,在render調(diào)用之后

void componentDidUpdate(prpos,state)

組件更新完畢,接收prposstate新的參數(shù),propsstate是新的傳入對(duì)象,當(dāng)組件更新完成調(diào)用,可多次調(diào)用
s
void componentWillReceiveProps(prpos)

父控件向子控件傳值,組件將要收到新的值, 接收prpos新的參數(shù),可多次調(diào)用

void componentWillUnmount()

組件卸載(webStorm會(huì)自動(dòng)提示補(bǔ)全成componentWillUnMount,這是錯(cuò)誤的),調(diào)用一次

bool shouldComponentUpdate(prpos,state)

組件是否重新繪制 接收prposstate新的參數(shù),可多次調(diào)用

該方法是用來(lái)優(yōu)化的react性能的,可以判斷新的props和以前的props值是否發(fā)生改變來(lái)決定是否重新繪制組件

return true 重新繪制

return false 不重新繪制

例子

class CustomButton extends Component {
    constructor(props){
        super(props)
        this.state = {
            count:0
        }
    }
    componentWillMount() {
        console.log("componentWillMount")
    }
    componentDidMount() {
        console.log("componentDidMount")
    }
    componentDidUpdate(nextProps, nextState) {
        console.log("componentDidUpdate")
    }
    componentWillReceiveProps(props) {
        console.log("componentWillReceiveProps",props);
    }
    componentWillUnmount() {
        console.log("componentWillUnmount")
    }
    shouldComponentUpdate(nextProps, nextState) {
        console.log("shouldComponentUpdate",nextProps);
        return true;
    }
    onClick(){
        this.setState(
            {
                count:++this.state.count
            }
        )
        console.log("控件更新組件的props")
    }

    render(){
        return(
            <button onClick={()=>this.onClick()}>
                {this.state.count}
            </button>
        )
    }
}
class HelloState extends React.Component {
  constructor(props) {
      super(props);
      this.state = {
          loading:true,
          update:""
      };
  }
  click(){
      console.log("卸載組件")
    this.setState({loading:false})
  }
    update(){
      console.log("父控件更新組件的props")
        this.setState({update:"1"})
    }
  render (){
    return (
        <div>
            <button onClick={this.click.bind(this)}>卸載</button>
            <button onClick={this.update.bind(this)}>更新</button>
            {this.state.loading ?<CustomButton update={this.state.update}/>:null
            }
        </div>
    )
  }
}

運(yùn)行結(jié)果

點(diǎn)擊CustomButton,再點(diǎn)擊更新,最后點(diǎn)擊卸載的運(yùn)行的日志如下

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容