为什么mapStateToProps中的状态未定义?

时间:2018-06-27 03:14:39

标签: reactjs redux react-redux

reducers / counter.js

export type counterStateType = {
  +ctr: number,
  +counter: boolean
};

type actionType = {
  +type: string,
  +value: any
};    

export default function counter(state: counterStateType = { ctr: 0, counter: true}, action: actionType) {
  console.log("Reducer called with");
  console.log(state);//has valid value ie { ctr: 0, counter: true}  
  switch (action.type) {
    case TOGGLE:
      state.counter = !state.counter;
      return state;
    case UPDATE:
      state.ctr = action.value;
      return state;
    default:
      return state;
  }
}

enter image description here

counterPage.js

function mapStateToProps(state) {
  console.log("mapStateToProps called with");
  console.log(state.counter);

  return {
    ctr: state.counter.ctr,//<= undefined
    counter: state.counter.counter
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(CounterActions, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(Counter);

enter image description here

PS:以上内容在路由器LOCATION_CHANGE上

1 个答案:

答案 0 :(得分:0)

问题出在减速器中,我忘记了redux状态的不变性。修改

  switch (action.type) {
    case TOGGLE:
      state.counter = !state.counter;
      return state;
    case UPDATE:
      state.ctr = action.value;
      return state;
    default:
      return state;
  }

  switch (action.type) {
    case TOGGLE:
      return {ctr: state.ctr, counter: !state.counter};
    case UPDATE:
      return {ctr: action.value, counter: state.counter};
    default:
      return state;
  }

解决了。