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

后端 未结 3 498
甜味超标
甜味超标 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:38

    Your approach to use both redux store and local store is correct.

    Just do not try to duplicate the state from redux store in your component. Keep referring to it via props.

    Instead create a sortedContacts function that computes value on the fly by applying locally-stored sortBy param to redux-stored contacts.

    const Table extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          sortBy: 'id' // default sort param
        }
      }
    
      sortContacts(param) {
        this.setState({ sortBy: param})
      }
    
      sortedContacts() {
        return this.props.contacts.sort(...); // return sorted collection
      }
    
      render() {
        return (
          
              {this.sortedContacts()}
            
    this.sortContacts("firstName")}>First Name
    ) } }

提交回复
热议问题