componentWillReceiveProps中调用的动作进入无限循环。

时间:2017-07-11 11:44:54

标签: reactjs redux react-redux redux-saga

在我的应用程序中,有一个阶段和游戏对应一个阶段。我在componentDidMount中获取阶段然后在componentWillReceiveProps中,我检查reducer中是否有stageId,然后获取阶段的游戏。用于获取游戏的动作阶段被无限次触发。有人解释为什么?

componentDidMount() {
  this.props.fetchCurrentStage();
}

componentWillReceiveProps(nextState) {
  if (nextState.stageReducer && nextState.stageReducer.stageId) {
    this.props.fetchGamesForStage(nextState.stageReducer.stageId);// Corresponding action is triggered infinite times.Why?
  }
}

1 个答案:

答案 0 :(得分:1)

正如您所提到的,I check if there is stageId in reducer,我假设您已经编写了mapStateToProps函数,如下所示:

const mapStateToProps = (state) => {
  return {
    stageReducer: state.stageReducer,
  }
}

如果你写mapStateToProps这样的话会很棒:

const mapStateToProps = (state) => {
  return {
    stageId: state.stageReducer ? state.stageReducer.stateId : undefined,
  }
}

stageId而不是整个stateReducer传递stateReducer,您可以将较早的stateIdstageId中的新componentWillReceiveProps进行比较,如下所示:< / p>

componentWillReceiveProps(nextProps) {
    if (nextProps.stageId && this.props.stageId !== nextProps.stageId) {
      this.props.fetchGamesForStage(nextState.stageId);// Corresponding action is triggered infinite times.Why?
    }
}

当第一次调用componentWillreceiveProps时,this.props.stageId !== nextProps.stageId将被评估为true。因此,将触发相应的操作。

有疑问:我认为当从服务器获取stageReducer的结果时,您正在更改fetchGamesForStage的引用。这就是为什么再次调用componentWillReceiveProps的原因。

如果这是正确的,则从stageReducer

发送mapStateToProps中的所选项目
 const mapStateToProps = (state) => {
      return {
       // other things from stageReducer

        stageId: state.stageReducer ? state.stageReducer.stateId : undefined,
      }
    }

或者,如果您不想更改结构,那么这也可能会有所帮助:

componentWillReceiveProps(newProps) {
  const oldStageId = this.props.stageReducer ? this.props.stageReducer.stageId : undefined
  const newStageId = newProps.stageReducer ? newProps.stageReducer.stageId : undefined
  if (newStageId && oldStageId !== newStageId) {
    this.props.fetchGamesForStage(newStageId);// Corresponding action is triggered infinite times.Why?
  }
}

希望,这有帮助。