简体   繁体   中英

Reducer not called after action is dispatched

I'm trying to get started on react/redux using the boilerplate code from http://reactboilerplate.com and it worked great until now.

I want to update my state from a container, and I'm dispatching a call like this:

// 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);

I thought that the dispatch(updateMoneyValue(newMoneyValue)) should actually dispatch the action and have it hit the reducer. But actually what happens is that when I perform the call in the first line, my action is triggered:

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

But the reducer never runs:

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;
  }
}

I tried to find the solution, but I'm really stuck on this one and would appreciate any help!

Best regards, Ayaka.

change:

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

to:

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

edit: that way, you "set the new state", without the state = you are changing the state but not using the changed state to later return it

When you map the state or dispatch your method become available in the props.

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

When you're calling updateMoneyValue(newValue) , you're not dispatching the action, you're calling the action creator directly.

To go through Redux, you need to call this.props.updateMoneyValue(newValue)

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