简体   繁体   中英

Redux, react. How I can add mapStateToProps into this.state?

I have action and middleware, where I make a fetch request. I get a data in mapStateToProps.

But I want use this data in my state and change them in setState. How I can add mapStateToProps into this.state?

I want filter my data on client side. If I dispatch my action I was make request to my server, it does not have to be done, because we have all list in our store.

You can achieve this by updating component's state once a redux store is updated (say, dispatched fetch success action) and component receives new values.

However, this is not idiomatic in most cases, since now you have to deal with possible desync of local component state and external redux state (which can be updated from outside of our component AND these new values will be passed down to our component).
Of course, you can ignore those changes and do nothing on props change.
Or reverse - update the state of component every time new props arrive.

Here is an example of syncing props and state:

// get `value` from store and pass it as prop to our component
const mapStateToProps = state => ({ value: state.someKey.value })

class Component extends React.Component {
  // new props has been passed
  // this method receives new props and current state
  // returns next state values, or null if no changes required
  static getDerivedStateFromProps(props, state) {
    // some complex comparison logic goes here
    // if true, then desync happened, let's update local state
    if (state.value !== props.value) {
      // this value will be at `this.state.value`
      return { value }
    }

    // else, no update needed for our state
    return null
  }

  // initial values taken from props
  state = { value: this.props.value }

  // update local state
  onChange = e => this.setState({ value: e.target.value })

  // let's render props value as label and state values as input value
  render() {
    return (
      <label>
        Props value is {this.props.value}
        <input value={this.state.value} onChange={this.onChange} />
      </label>
    )
  }
}

Note, that getDerivedStateFromProps is a relatively new lifecycle method (similar to "old" componentWillReceiveProps ) and this use case is mentioned in official docs as a possible sign of bad design.

TL;DR duplicating state is bad, especially if we have to sync it manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM