关于React16中的componentWillUnmout
问题
最近在升级React的时候遇到一个奇怪的问题:当我们在另一个页面(以下称原始页)切换另一个页面(目标页)的时候,所期望的是在原始页中的数据重置,在目标页使用重置的数据。
理想很丰满,现实很残酷。
当切换至目标页面的时候,数据还是原始的。测试就开始报bug了。。。
想法
然后我仔细想了一下,我们在React15中,React团队使用的是同步渲染,也就是说,当一个组件离开后(componentWillUnmount),再去开始下一个组件的调用(constructor)。但是在React16中,React采用的是Fiber的架构去实现渲染的,它的大体思路就是组件异步渲染,具体可以去看看React的官方演讲Google
过程
然后我在codepan上面试了相同代码在15、16版本下的不同
class Test extends React.Component { constructor (props) { super(props) console.log('Test constructor') } componentWillMount () { console.log('Test componentWillMount') } componentDidMount () { console.log('Test componentDidMount') } componentWillUnmount () { console.log('HelloWorld componentWillUnmount') } render () { return ( <div>I am test!</div> ) } }
class HelloWorld extends React.Component { constructor (props) { super(props) console.log('HelloWorld constructor') } componentWillMount () { console.log('HelloWorld componentWillMount') } componentDidMount () { console.log('HelloWorld componentDidMount') } componentWillUnmount () { console.log('HelloWorld componentWillUnmount') } render () { return ( <div>I am hello world!</div> ) } }
class App extends React.Component { constructor(props) { super(props); this.state = { status: 1 } this.handleClick = this.handleClick.bind(this) } handleClick () { this.setState({ status: this.state.status === 1 ? 2 : 1 }) } render () { return ( <div> {this.state.status === 1 ? ( <HelloWorld /> ) : ( <Test /> )} <button onClick={this.handleClick}>点击我</button> </div> ) } }
ReactDOM.render( <App />, document.getElementById('app') )
|
15版本 codepen
16版本 codepen
结论
在16版本里面我们需要改变下数据的生命周期。
- 在使用初始数据的时候在「constructor / componentWillMount」中初始化数据
- 在「componentWillUnmout」中注销事件