所以我是 redux-toolkit 的新手,我想做一些非常简单的事情。我想通过这个辅助函数发送一些关于 POST 请求的数据。所以我尝试了这个
export const submitPaymentToServer = createAsyncThunk(
'data/fetchAll',
async ({ name, data }) => {
return fetch('/payments', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
data,
}),
})
.then((res) => res.json())
.then((res) => res)
},
)
但是当我这样调用它时 dispatch(
submitPaymentToServer({
name,
data,
}),
)
typescript 提示说我没有正确数量的参数。那么我应该如何将 args 传递给这个函数呢?或者用工具包做到这一点的方法是什么?
最佳答案
这是 React-Redux 在你使用 createAsyncThunk
时所说的。
You can only pass one argument to the thunk when you dispatch it. If you need to pass multiple values, pass them in a single object
所以而不是
export const submitPaymentToServer = createAsyncThunk(
'data/fetchAll',
async ({ name, data }) => { // here you have two arguments
return fetch('/payments', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
data,
}),
})
.then((res) => res.json())
.then((res) => res)
},
)
你只能有一个论点:export const submitPaymentToServer = createAsyncThunk(
'data/fetchAll',
async (yourData) => {
const {name, data} = yourData;
return fetch('/payments', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
data,
}),
})
.then((res) => res.json())
.then((res) => res)
},
)
解构 thunk
中的对象称呼。引用:here
关于javascript - 如何在 redux 工具包中将参数传递给 createAsyncThunk?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64742747/