我一直在使用Redux-Toolkit
超过React-Redux
. 我遇到了我必须提出GET
请求的情况,所以我最近开始使用Redux-Thunk
(在此之前我使用useEffect
但是,因为它不是处理函数的标准方式async
,使用 redux 时。我了解了middleware
)。
这是我Thunk function
处理请求的代码extraReducer
GET
export const fetchData = createAsyncThunk("type/getData", async () => {
try {
const response = await axios({url});
return response.data;
} catch (error) {
console.log(error.response);
}
});
export const extraReducers = {
[fetchData.pending]: (state) => {
state.loading = true;
},
[fetchData.fulfilled]: (state, action) => {
state.loading = false;
state.products = action.payload;
},
[fetchData.rejected]: (state) => {
state.loading = false;
state.error = true;
},
};
在fetchData
函数中,我的返回response.data
值被使用,extraReducers
因此payload
我可以轻松设置状态。但是,现在的情况是我发出了一个发布请求,但我不知道如何将数据发送到我的Thunk
函数。
首先,您创建发布数据的操作并发送data
:
export const postData = createAsyncThunk(
"type/postData",
async (data) => {
try {
const response = await axios.post("https://reqres.in/api/users", data);
// If you want to get something back
return response.data;
} catch (err) {
console.error(err)
}
}
);
然后在您想要发送该数据的地方,您只需使用data
您想要发送的参数发送此操作:
const handlePost = () => {
// whatever you want to send
const data = .........
dispatch(postData(data));
}
如果你愿意,你也可以修改你的extraReducers
for this action。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句