How does a redux connected component know when to re-render?

后端 未结 4 1838
逝去的感伤
逝去的感伤 2020-12-07 07:49

I\'m probably missing something very obvious and would like to clear myself.

Here\'s my understanding.
In a naive react component, we have states &

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-07 08:27

    My answer is a little out of left field. It sheds light on a problem that led me to this post. In my case it seemed the app was Not re-rendering, even though it received new props.
    React devs had an answer to this often asked question something to the tune that if the (store) was mutated, 99% of the time that's the reason react won't re-render. Yet nothing about the other 1%. Mutation was not the case here.


    TLDR;

    componentWillReceiveProps is how the state can be kept synced with the new props.

    Edge Case: Once state updates, then the app does re-render !


    It turn out that if your app is using only state to display its elements, props can update, but state won't, so no re-render.

    I had state that was dependent on props received from redux store. The data I needed wasn't in the store yet, so I fetched it from componentDidMount, as is proper. I got the props back, when my reducer updated store, because my component is connected via mapStateToProps. But the page didn't render, and state was still full of empty strings.

    An example of this is say a user loaded an "edit post" page from a saved url. You have access to the postId from the url, but the info isn't in store yet, so you fetch it. The items on your page are controlled components - so all the data you're displaying is in state.

    Using redux, the data was fetched, store was updated, and the component is connected, but the app didn't reflect the changes. On closer look, props were received, but app didn't update. state didn't update.

    Well, props will update and propagate, but state won't. You need to specifically tell state to update.

    You can't do this in render(), and componentDidMount already finished it's cycles.

    componentWillReceiveProps is where you update state properties that depend on a changed prop value.

    Example Usage:

    componentWillReceiveProps(nextProps){
      if (this.props.post.category !== nextProps.post.category){
        this.setState({
          title: nextProps.post.title,
          body: nextProps.post.body,
          category: nextProps.post.category,
        })
      }      
    }
    

    I must give a shout out to this article that enlightened me on the solution that dozens of other posts, blogs, and repos failed to mention. Anyone else who has had trouble finding an answer to this evidently obscure problem, Here it is:

    ReactJs component lifecycle methods — A deep dive

    componentWillReceiveProps is where you'll update state to keep in sync with props updates.

    Once state updates, then fields depending on state do re-render !

提交回复
热议问题