问题描述
所以我收到一条错误消息,指出未定义.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
的初始状态指定为空数组,否则我建议您显示一个空文本或某种加载程序,直到在dealershipGoalType
中得到任何东西为止。
{
dealershipGoalType.length > 0 ?
dealershipGoalType.map(goal => (
<option value={goal.type_goal}>
{goal.label}
</option>
)
: <span> There are no listings! </span>
}
,
您可以使用ES2020中出现的 Nullish合并运算符。在渲染中,使用
let dealershipGoalType = this.props.dealershipGoalType ?? [];
这样,如果DealershipGoalType为空,它将自动分配一个空数组DealershipGoalType而不会破坏代码。而且,它减少了为解决此问题而要编写的代码量,并使代码看起来也很干净。
您可以详细了解here。