How do I use local state along with redux store state in the same react component?

后端 未结 3 510
甜味超标
甜味超标 2020-12-30 03:16

I have a table that displays contacts and I want to sort the contacts by first name. The contacts array comes from the redux store, which will come then come through the pro

3条回答
  •  我在风中等你
    2020-12-30 03:58

    The componentWillReceiveProps() method is not called for the initial render. What could do, if you only intend to use the data from props as the initial data, is something like:

    getInitialState () {
      return {
        contacts: this.props.data.contacts
      }
    }
    

    In the React docs they suggest you name the props initialContacts, just to make it really clear that the props' only purpose is to initialize something internally.

    Now if you want it to update when this.props.contacts change, you could use componentWillReceiveProps() like you did. But I'm not sure it's the best idea. From the docs:

    Using props to generate state in getInitialState often leads to duplication of "source of truth", i.e. where the real data is. This is because getInitialState is only invoked when the component is first created.

    Whenever possible, compute values on-the-fly to ensure that they don't get out of sync later on and cause maintenance trouble.

提交回复
热议问题