我在 useEffect
钩子中有以下几行代码,它不会返回我期望的结果:
useEffect(() => {
console.log('===========================');
console.log('chatState.customers');
console.log(chatState.customers);
console.log(chatState.customers?.length);
if (chatState !== undefined && chatState.customers && chatState.customers.length > 0) {
const name = 'Yoges Gamuda';
const result = chatState.customers.filter((obj) => {
return obj.name === name;
});
console.log(`result for name ${name} is: `);
console.log(result);
const p = chatState.customers.find((x) => x.name === name);
if (p !== undefined) {
console.log(`p >> id: ${p.id} name: ${p?.name}`);
} else {
console.log('p is undefined!');
}
console.log('===========================');
}
}, [chatState]);
结果:
我从上面注意到:
chatState.customers
确实包含数据chatState.customers
的类型为 array
,长度为 39
Yoges Gamuda
”)确实存在于 chatState.customers
背景详情:
chatState
来自 Context
:
const { state: chatState } = chatContext;
定义如下:
我做错了什么?我已经研究了一天,但我仍然无法弄清楚。
编辑添加
我尝试打印 chatState.customers
的值,结果如下:
chatState.customers.forEach((x) => console.log(x));