ComponentWillMount only trigger for first time?

时光毁灭记忆、已成空白 提交于 2019-12-04 19:12:37

First I would like to point out you should not use componentWillMount life cycle method since it has been deprecated on last minor update of React 16.3

Heres list of deprecated life cycle methods, (componentWillMount, componentWillReceiveProps, and componentWillUpdate). You can read more about deprecated life cycle methods here.

Secondary in your example life cycle works as expected. componentWillMount triggers only once since your component will be initial rendered/mounted only one time and that's how React works.

I would work this out with following method.

Add getDerivedStateFromProps life cycle to Content component, which will trigger when component receives new props and as well on initial mount.

static getDerivedStateFromProps(nextProps, prevState) {
  console.log('will log on props change');
  if( nextProps.contentDate !== prevState.contentDate ) {
    return { contentDate: nextProps.contentDate };
    // Notice we return plain object here to update state
  }
  return null;
  // return null when changes are not needed
}

This example checks that contentDate has changed and if so pushes it into component -state. And on render method you get it by this.state.contentDate.

render() {
  return (
    <View><Text>{this.state.contentDate}</Text></View>
  );
}

You could achieve similar behaviour with implementing this in componentDidUpdate but then you have much bigger risk to end up with infinite loops and much worse performance. But it's possible just have strong checks that data you have expected has really changed as you would expect. Then you can do setState and component re-renders.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!