首页 > 解决方案 > 从 fetch api 返回数组到 reducer

问题描述

这有效:

const initialState = [
  { id: 1, title: 'This way', completed: true },
  { id: 3, title: 'array definition works', completed: true },
  { id: 2, title: 'As expected', completed: false },
];

硬编码数组按预期工作,但如果我尝试从异步获取 api 动态获取值,则:

“拼命尝试让它发挥作用”

(async () => {
  initialState.push(getPostAsync('/posts').then(data =>[
    { id: 1, title: data.title, completed: true },
    { id: 3, title: 'This way doesnt', completed: false },
    { id: 2, title: 'work ', completed: false }]));
})();

export const filterForum = (forums, searchKeyword) => (
  Object.values(forums).filter(forum => forum.title.includes(searchKeyword))
)

× TypeError:无法读取未定义的属性“包含”

标签: javascriptnode.js

解决方案


根据您的回复,forums您传递给的变量filterForum(我将其称为 filterForums 但 W/E)未定义。因此,当您尝试对其调用 .filter 时,它会爆炸,因为 .filter 未在未定义的变量上定义。


推荐阅读