如何使用redux thunk和redux工具包提出发布请求
我一直使用redux-toolkit
比react-redux
更多。我遇到了必须进行get
请求的情况,因此我最近开始使用redux-thunk
(在此之前,我使用useffect
当我使用redux时,这不是一种标准方法处理 。
这是我的thunk函数的代码
nad extrareducer
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;
},
};
在get> get
replect> fetchdata 中处理 > response.data 在extrareducers
中使用有效载荷
,因此我可以轻松设置状态。但是,现在的情况是我已经提出了发布请求,我不知道如何将数据发送到我的thunk
函数。
I have been using Redux-Toolkit
more than the React-Redux
. I came across situations where I had to make GET
requests, So I recently started using Redux-Thunk
(before this I used useEffect
but, as it's not a standard way to handle async
functions, when using redux. I learned about middleware
).
Here is the code of my Thunk function
nad extraReducer
which handles the GET
request
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;
},
};
In fetchData
function my returned response.data
is being used in extraReducers
as payload
so I can set the state easily. But, now the scenario is I have make a post request and I don't know how will I send the data to my Thunk
function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您创建发布数据的动作,然后发送
数据
:然后在要发送数据的地方,只需使用
data
参数,发送:如果您愿意,也可以为此操作修改
extrareducer
。First you create the action of posting data and send the
data
:Then in a place where you want to send that data you just dispatch this action with the
data
argument that you want to send:If you want, you can also modify your
extraReducers
for this action.