【发布时间】:2022-01-10 12:48:52
【问题描述】:
我有一个 reducer 函数,我必须在其中进行 API 调用,然后将其结果作为状态返回。但由于 API 调用是异步的,因此 state 的值不会更新。
if (action.type==='CREATE_POST') {
const x= async () => {
const res=await fetch("http://localhost:5000/posts", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(
action.payload
)
})
const data= await res.json()
return data
}
return [...state,x]
}
我也试过了
if (action.type==='CREATE_POST') {
const x= async () => {
const res=await fetch("http://localhost:5000/posts", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(
action.payload
)
})
const data= await res.json()
return data
}
return [...state,x().then((data)=>{console.log(data);})]
}
【问题讨论】:
-
你的 redux reducer 代码在哪里?
标签: javascript reactjs asynchronous async-await fetch