How to create a React component to setState () based on Redux state change?

I think I know the answer to this question, but just to make sure:

I want the React component to call this.setState()when a Redux state goes into a specific state (like state.dataLoaded === true). Should I use it in some way subscribe, or is it too low, and instead, should I use it connectto match state with details? In this case, I assume that this would be acceptable:

componentWillReceiveProps(nextProps) {
  if (nextProps.dataLoaded) {
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(nextProps.posts)
    });
  }
}
+4
source share
1 answer

You must use connectfor this. When the state of reduction changes, new details will be created and will cause componentWillReceiveProps.

class MyComp extends React.Component {
  componentWillReceiveProps(nextProps) {
    if (nextProps.dataLoaded) {
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(nextProps.posts)
      })
    }
  }
}

export default connect(
  state => ({
    dataLoaded: state.someStore.loaded
  })
)(MyComp)
+10

Source: https://habr.com/ru/post/1627903/


All Articles