如何基于Redux状态更改生成React组件setState()?

ffx*_*sam 8 reactjs redux

我知道答案,但只是为了确保:

我希望this.setState()在Redux状态更改为某个条件(例如state.dataLoaded === true)时调用React组件.我应该以某种方式使用subscribe,或者是太低级别我应该使用connect将状态映射到道具?在这种情况下,我认为这样的事情是可以接受的:

componentWillReceiveProps(nextProps) {
  if (nextProps.dataLoaded) {
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(nextProps.posts)
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

Flo*_*ent 14

你明确应该connect这样做.当redux的状态发生变化时,将生成新的道具并触发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)
Run Code Online (Sandbox Code Playgroud)