React生命周期
前言React组件的生命周期可以分为挂载,渲染和卸载这几个阶段。 一.挂载或卸载过程1.组件初始化 static defaultProps保证this.props有初始值 this.state初始值 componentWillMount会在render之前调用,componentDidMount会在render之后调用,分别代表了渲染前后的时刻, 都只执行一次。 render之后,我们在componentDidMount中执行setState,组件会再次render,不过在初始化过程就渲染了两次组件 ,这并不是一件好事,但实际情况是,有些场景不得不需要setState,比如计算组件的位置或宽高等,就不得不让组件 先渲染,更新必要的信息后,再次渲染。 2.组件的卸载: componentWillMount() { this.setState({ a: this.state.a + 1 // 先执行willMount,a + 1,再执行render,componentDidMount }); console.log('will' + this.state.a); } componentDidMount() { console.log('did' + this.state.a); } render() { console.log('render' + this.state.a); return ( <div> <div><button onClick={ this.add }>home</button></div> <div>{ this.state.a }</div> <div>{ this.props.maxLoops }</div> <About2 id={ this.state.a } /> </div> ); } 二.数据更新过程1.数据更新过程: componentWillReceiveProps(nextProps) { console.log('willreceive'); console.log(nextProps); if (nextProps.id === 4) { this.setState({ bb: 1000 }) } } shouldComponentUpdate(nextProps,nextState) { console.log('should update'); if (nextState.bb === 16) { return false; } return true; } componentWillUpdate(nextProps,nextState) { console.log('will update'); } componentDidUpdate(prevProps,prevState) { console.log('did update'); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |