【问题标题】:Reducer not called after action is dispatched调度操作后未调用减速器
【发布时间】:2018-08-26 13:05:05
【问题描述】:

我正在尝试使用来自 http://reactboilerplate.com 的样板代码开始 react/redux,它一直运行良好。

我想从一个容器中更新我的状态,我正在发送这样的调用:

// This is the method that should tigger the action
updateMoneyValue(newValue);

...

// Here I hope I set up everything correctly...
function mapDispatchToProps(dispatch) {
  return {
    updateMoneyValue: newMoneyValue =>
      dispatch(updateMoneyValue(newMoneyValue)),
  };
}
const withConnect = connect(
  mapStateToProps,
  mapDispatchToProps,
);

const withReducer = injectReducer({ key: 'counterPage', reducer });
const withSaga = injectSaga({ key: 'counterPage', saga });

export default compose(
  withReducer,
  withSaga,
  withConnect,
)(CounterPage);

我认为dispatch(updateMoneyValue(newMoneyValue)) 实际上应该调度动作并让它命中减速器。但实际上发生的是,当我在第一行执行调用时,我的操作被触发:

export function updateMoneyValue(moneyValue) {
  console.log('Action has fired.');
  return {
    type: UPDATE_MONEY_VALUE,
    moneyValue,
  };
}

但是reducer永远不会运行:

function counterPageReducer(state = initialState, action) {
  switch (action.type) {
    case UPDATE_MONEY_VALUE:
      console.log('Reducer was called.');
      state.set('moneyValue', action.moneyValue);
      return state;
    default:
      return state;
  }
}

我试图找到解决方案,但我真的被困在这个问题上,希望能提供任何帮助!

最好的问候, 绫香。

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

    当您调用 updateMoneyValue(newValue) 时,您并不是在调度操作,而是直接调用操作创建者。

    要通过Redux,你需要调用this.props.updateMoneyValue(newValue)

    【讨论】:

    • 非常感谢!
    • 非常感谢
    【解决方案2】:

    当您映射状态或调度您的方法时,您的方法在道具中可用。

    // This is the method that should tigger the action
    this.props.updateMoneyValue(newValue);
    

    【讨论】:

      【解决方案3】:

      改变:

      state.set('moneyValue', action.moneyValue);

      到:

      state = state.set('moneyValue', action.moneyValue);

      编辑:这样,您“设置新状态”,没有state =,您正在更改状态,但不使用更改后的状态来返回它

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-02
        • 2021-01-13
        • 1970-01-01
        • 1970-01-01
        • 2017-10-18
        • 2020-02-07
        • 1970-01-01
        • 2020-09-21
        相关资源
        最近更新 更多