javascript - API调用期间如何在reducer函数中返回状态
问题描述
我有一个 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 个文件,命名为:
- 减速器.js
- 动作.js
- effect.js(用于异步任务)
在减速机
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.js
export 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));
});
};
};
推荐阅读
- java - 由于路径中的“#”字符,未找到 XSD
- react-native - 如何更改 Android 的 React Native DateTime Picker 语言环境?
- php - 由于没有可用的匹配包,无法将 PHP 升级到 7.3
- c - 如何在标准C中正确使用双指针(指向指针的指针)作为结构数组?
- python - 当参数被编码时,Fastapi 的行为不同
- javascript - Vue js在v-if内的表格行中输入
- python - 如何使 MissingPermissions 命令处理程序的格式更好?
- javascript - 函数无法使用 useEffect 访问即时状态更改
- postgresql - 我可以假设所有数据库都会返回一个承诺吗?
- amazon-web-services - 如何将 S3 对象从一个 AWS 账户复制到另一个?