0
votes

I'm writing a SPA using Redux to manage my state. There is a logic component connected to the redux store, and it has a child component and it transport the 'posts' state by props to the child component. In the child component's render function:

const {onShow,posts} = this.props;

It works well; just the posts will change with the redux store. But in its componentDidMount() function or construct function the posts will not change with redux store, so how could it happen?

componentDidMount(){
   const {posts} = this.props;
   console.log(posts)
}

Here are the complete components code. It's about the Lists component and Posts component.

1
you can get the new props as componentWillReceiveProps(nextProps) { console.log(nextProps.posts } - Rei Dien
Yeah, that's right, but I don't know why the posts will not change in componentDidMount function, - laoqiren
componentDidMount does not trigger on props change, it will only trigger on initial render.facebook.github.io/react/docs/react-component.html - Rei Dien
Because componentDidMount() only gets fired when the component is... well, mounted (i.e., rendered to the UI). Or such is my interpretation. - IsenrichO
the react router navigate will make the parent logic component remount and then the child will remount,too. And the componentDidMount runs again indeed. - laoqiren

1 Answers

0
votes

As I understand from your post, you are wondering about why you are not able to see the reflection of state update inside of componentDidMount().

It's because componentDidMount function is called when instance of a react component is being created and inserted into the DOM. It's called in mounting phase of a react component's lifecycle.

To be able to see your reflections of redux state update, you need to use functions which are called at the update stage such as:

  • componentWillReceiveProps()
  • componentDidUpdate()
  • shouldComponentUpdate()

To get more detailed information, please check component lifecycle documentation:

https://facebook.github.io/react/docs/react-component.html