.map 在 this.props.action 执行之前未定义

.map is undefined before this.props.action executes

所以我收到一条错误消息,指出 .map 未定义,因为我假设 this.props.action 未完成,因此使 .map 无法映射任何内容。

减速机

 case GET_DEALERSHIP_GOAL_TYPE_SUCCESS:
      return Object.assign({}, state, {
        loading: false,
        dealershipGoalType: action.payload.data
      });

mapStateToProps

const mapStateToProps = state => ({
  dealershipGoalType: state.DealerPreferencesReducer.dealershipGoalType,
});

componentDidMount

  componentDidMount = () => {
      this.props.actions.getDealershipGoalType(this.state.prevId, this.state.year)
  };

渲染

render = () => {

 let {dealershipGoalType } = this.props;
}

地图部分

  {dealershipGoalType.map(goal => (
      <option value={goal.type_goal}>
        {goal.label}
      </option>
  ))}

有什么想法吗?

您可以将 dealershipGoalType 的初始状态指定为一个空数组,除此之外我建议您显示一个空文本或某种加载器,直到您在 [=11= 中得到任何东西].

{
  dealershipGoalType.length > 0 ?
   dealershipGoalType.map(goal => (
    <option value={goal.type_goal}>
     {goal.label}
    </option>
  )
 : <span> There are no listings! </span>
}

您可以使用 ES2020 中出现的 Nullish Coalescing Operator。在你的渲染中,使用

let dealershipGoalType = this.props.dealershipGoalType ?? [];

这样如果dealershipGoalType为空,它会自动分配一个空数组dealershipGoalType而不破坏代码。而且,它减少了为解决这个问题而编写的代码量,并且使代码看起来也很干净。

您可以阅读更多相关信息 here