我想将Redux存储ID与动作有效负载ID进行比较,并使用find方法更新Redux存储状态。当我第三次比较相同值时,find方法仅起作用两次,所以find方法给我这个错误:
TypeError:无法读取未定义的属性“ find”
const initialState = {
frontendCategory: [],
backendCategory: [],
devOpsCategory: [],
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.ADDED_USER_TO_FRONTEND_CATEGORY:
let updateddata = state.frontendCategory.find(data => data.id === action.payLoad.id);
if (updateddata) {
return [...state.frontendCategory];
}
return {
...state,
frontendCategory: state.frontendCategory.concat(action.payLoad),
};
}
};
export const addedUserToFrontendCategory = (GithubUserId) => {
return {
type: actionTypes.ADDED_USER_TO_FRONTEND_CATEGORY,
payLoad: {
id: GithubUserId,
},
};
};
答案 0 :(得分:0)
当您的更新数据变为true时,您将状态从包含fontendCategory的对象更改为包含来自frontendCategory的属性的数组。
当发生这种情况时,您会收到此错误,因为您的状态现在是一个数组,并且没有fontendCategory作为属性。
也许您应该总是返回一个对象。像这样:
if (updateddata) {
return state; // or return your business rule, but always an object contains frontendCategory as an array
}
return {
...state,
frontendCategory: state.frontendCategory.concat(action.payLoad),
};