首页 > 解决方案 > 为什么 mapStateToProps 中的状态未定义?

问题描述

减速器/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;
  }
}

在此处输入图像描述

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

在此处输入图像描述

PS:以上是在路由器 LOCATION_CHANGE

标签: reactjsreduxreact-redux

解决方案


问题出在 reducer 中,我忘记了 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;
  }

解决了。


推荐阅读