TypeScript:“过滤器”和“查找”未返回预期结果

时间:2021-01-30 13:51:33

标签: javascript arrays typescript

我在 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]);

结果:

enter image description here

我从上面注意到:

  • chatState.customers 确实包含数据
  • chatState.customers 的类型为 array,长度为 39
  • 我正在寻找的密钥(“Yoges Gamuda”)确实存在于 chatState.customers

背景详情:

  • chatState 来自 Context:

    const { state: chatState } = chatContext;
    
  • 定义如下:

enter image description here

enter image description here

enter image description here

我做错了什么?我已经研究了一天,但我仍然无法弄清楚。

编辑添加

我尝试打印 chatState.customers 的值,结果如下:

chatState.customers.forEach((x) => console.log(x));

enter image description here

0 个答案:

没有答案