我有一个 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);})]
}
最佳答案
如果您正在执行异步任务,我建议您使用以下模式:
创建 3 个文件,命名为:
在 reducer
const initialState = {
loading: false,
data: [],
error: ''
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case "FETCH_REQUEST":
return {
...state,
loading: true
}
case "FETCH_SUCCESS":
return {
loading: false,
data: action.payload,
error: ''
}
case "FETCH_FAILURE":
return {
loading: false,
data: [],
error: action.payload
}
default: return state
}
}
export default reducer
在 action.js 中export const fetchRequest = () => {
return {
type: "FETCH_REQUEST"
}
}
export const fetchSuccess = data => {
return {
type: "FETCH_SUCCESS",
payload: data
}
}
export const fetchFailure = error => {
return {
type: "FETCH_FAILURE",
payload: error
}
}
最后是 effect.jsexport const fetch = () => {
return (dispatch) => {
//Initializing the request
dispatch(fetchRequest());
//Calling the api
api()
.then((response) => {
// response is the data
dispatch(fetchSuccess(response));
})
.catch((error) => {
// error.message is the error message
dispatch(fetchFailure(error.message));
});
};
};
关于javascript - API调用期间如何在reducer函数中返回状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68533607/