Javascript 将数组从fetch api返回到reducer
这项工作:Javascript 将数组从fetch api返回到reducer,javascript,node.js,Javascript,Node.js,这项工作: 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动态获取值,则: “不顾一切地试图让它发挥作用” ×
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动态获取值,则:
“不顾一切地试图让它发挥作用”
×
TypeError:无法读取未定义的属性“includes”您就快到了:
您提供了一个未初始化、因此未解决的承诺作为回退初始状态
这意味着在理论上,为了得到这些值,你需要
reducer = (state = await initialState, ...)
但由于这是不可能的,您真正需要做的是从硬编码的[]
状态开始(或{list:[]}
)
并使用可能是异步的,填充下一个状态,并将结果馈送给同步减速器
完整示例:
// reducer.js
const initialState = [];
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'loadList': {
return [...state, ...action.payload.list]; // in case payload is {list: [...]}
}
default:
return state;
}
}
// actions.js
export const loadList = () => async dispatch => { // need to install redux-thunk to get the 'dispatch' closure
try {
const data = fetch(...);
dispatch({type: 'loadList', payload: {list: data}});
} catch (e) {
console.log(e);
}
}
请注意,操作是同步的,但可以使用redux thunk库使其异步 从您的回答中,您传递给
filterForum
的论坛
变量(我称之为filterForum,但W/E)未定义。因此,当您尝试对其调用.filter时,它会崩溃,因为.filter未在未定义的变量上定义 你能不能把那部分代码贴在论坛.filter
没有功能的地方?通常,当调用过滤器
的变量(在本例中为论坛
)不是数组时,会发生这种情况。我会做一个console.log(forums)
来查看代码中有哪些值。您在哪里使用forums.filter函数?forum.title.toLowerCase()的值是多少?(searchKeyword.toLowerCase())?还有,论坛的价值是什么?我看到了filterForum
函数的定义,但没有看到它的使用方式。我猜它可能被传递了一个不正确的值。从您的代码来看,forum
是一个对象。(forum.title
给人这样的印象。)如果是这样的话,filter
就不是一种可用的方法。您需要将其转换为数组。解析错误:不能在异步函数外使用关键字“wait”,如我所说,这是不可能的。理论上你需要解决它。稍等,使用示例编辑解析错误:无法在我添加的异步函数(async()=>{reducer=(state=await initialState)})之外使用关键字'await';但是“state”没有定义weaking我现在的代码“state”没有定义no undef
// reducer.js
const initialState = [];
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'loadList': {
return [...state, ...action.payload.list]; // in case payload is {list: [...]}
}
default:
return state;
}
}
// actions.js
export const loadList = () => async dispatch => { // need to install redux-thunk to get the 'dispatch' closure
try {
const data = fetch(...);
dispatch({type: 'loadList', payload: {list: data}});
} catch (e) {
console.log(e);
}
}