过滤函数在 React 中的数组上不起作用
2022-09-20
299
我使用
useReducer
从服务器获取数据,并对其执行一些操作,然后将其显示在表格上,为此我使用
filter()
,但它给了我一个
错误
,提示我的数据为
Undefined
UseReducer:
function savedEventsReducer(state, { type, payload }) {
switch (type) {
case "push":
return [...state, payload];
case "update":
return state.map((evt) =>
evt.id === payload.id ? payload : evt
);
case "delete":
return state.filter((evt) => evt.id !== payload.id);
default:
throw new Error();
}
}
const [SavedEvents, dispatchcallEvent] =
useReducer(savedEventsReducer, [])
useEffect(() => {
axios.get('http://localhost:8000/SavedEvents/').then(resp => {
dispatchcallEvent({ type: 'push', payload: resp.data });
})
}, [])
这些是过滤数据的操作函数:
const [Lables, SetLables] = useState([])
const filteredEvents = useMemo(() => {
if(SavedEvents[0]){
console.log(SavedEvents[0]); // it's gives me my Data and not Undefine.
console.log(SavedEvents);
return SavedEvents[0].filter((evt) => // this is the line that mentioned in Error
Lables
.filter((lbl) => lbl.checked)
.map((lbl) => lbl.label)
.includes(evt.label)
);}
}, [SavedEvents, Lables])
useEffect(() => {
SetLables((prevLabels) => {
if(SavedEvents[0]){
return [...new Set(SavedEvents[0].map((evt) => evt.label))].map(
(label) => {
const currentLabel = prevLabels.find(
(lbl) => lbl.label === label
);
return {
label,
checked: currentLabel ? currentLabel.checked : true,
};
}
);
}
});
}, [SavedEvents])
所有这些代码都在我的
Context
中,我在第一次渲染后使用它们,它们全部被渲染
错误:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'filter')
at ContextWrapper.js:58:1
at Array.filter (<anonymous>)
at ContextWrapper.js:58:1
at updateMemo (react-dom.development.js:15867:1)
at Object.useMemo (react-dom.development.js:16413:1)
at useMemo (react.development.js:1532:1)
at ContextWrapper (ContextWrapper.js:54:1)
这是 SavedEvents[0] :
1个回答
您应该在 SetLables 顶部添加另一个条件,例如:
useEffect(() => {
if(SavedEvents[0]){
SetLables((prevLabels) => {
// console.log(SavedEvents[0]);
return [...new Set(SavedEvents[0].map((evt) => evt.label))].map(
(label) => {
const currentLabel = prevLabels.find(
(lbl) => lbl.label === label
);
return {
label,
checked: currentLabel ? currentLabel.checked : true,
};
}
);
});
}
// console.log(Lables);
}, [SavedEvents])
Mohsen.RJ
2022-09-20