React Native填坑之旅--组件生命周期

这次我们来填React Native生命周期的坑。这一点非常重要,需要有一个清晰的认识。如果你了解Android或者iOS的话,你会非常熟悉我们今天要说的的内容。

基本上一个React Native的组件会经历三个阶段最终渲染在界面上,他们分别是:开始渲染、更新、卸载。

开始渲染:

componentWillMount

componentWillMount(): void

组件开始渲染的时候调用这个方法

componentDidMount

componentDidMount(): void

组件的渲染完成之后调用这个方法。子组件的componentDidMount方法会在父组件的前面调用。componentWillMountcomponentDidMount方法之前调用,这个时候组件还没有渲染完成。所以在componentWillMount里调用setState方法会立刻在render方法里看到更新了的数据。

更新

componentWillReceiveProps

componentWillReceiveProps(nextProps: Object): void

当有新的Props发送给组件的时候,这个方法被触发。最开始的render并不会调用这个方法! 使用这个方法可以在更新state,render方法被调用之前修改组件的props。在这个方法里可以使用this.props来使用旧的props。在这个方法里调用setState方法不会触发额外的render。

例如:

componentWillReceiveProps(nextProps) {
  this.setState({
    currentCategory: nextProps.category !== this.props.category
                      ? nextProps.category
                      : this.props.category
  });
}

shouldComponentUpdate

shouldComponentUpdate(nextProps: Object, nextState: Object): void

当收到新的props或者state的时候触发这个方法。默认情况下shouldComponentUpdate一直返回true。这个方法在第一次render的时候不会调用。当你确定props和state被设置为新的值以后不需要组件更新的时候返回false。之后render方法在本次的更新中就会被直接跳过,componentWillUpdatecomponentDidUpdate两个方法也不会被调用。

componentWillUpdate

componentWillUpdate(nextProps: Object, nextState: Object): void

在props或者state更新之后立即调用这个方法。这个方法不会在第一次render的时候调用。

render

render(): ReactElement<{}>

render方法被调用的时候,组件会根据新的this.propsthis.state绘制。render方法应该是一个纯方法。也就是说,它不修改组件的state,并且每次调用都返回相同的结果。当然,这个需要开发者来保证。

componentDidUpdate

componentDidUpdate(prevProps: Object, prevState: Object): void

每次组件更新之后调用。第一次render的时候不会调用。

卸载

componentWillUnmount(): void

组件被卸载之后调用。可以在这个方法里执行一些清理操作。