我通过useReducer从服务器获取数据,并对其执行一些操作并将其显示在表上,为此我使用了.Filter(),但它给出了一个错误,即我的数据未定义
这是我的减肥药:
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])
- 所有这些代码都在我的上下文中,我使用它们,在第一次呈现之后,所有这些代码都被呈现*
这就是我的全部错误:
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条答案
按热度按时间u59ebvdq1#
您应该在SetLables上添加另一个条件,如下所示: