gpt4 book ai didi

reactjs - 具有多个参数的 redux 工具包 reducer ? redux 工具包

转载 作者:行者123 更新时间:2023-12-05 01:23:59 29 4
gpt4 key购买 nike

鉴于此

export const slice = createSlice({
name: 'reducer',
initialState: {

},
reducers: {
test: (state, action) => {
console.log(action.payload) // 1
}

},

})

然后我运行这个

dispatch(test(1,2,3,4,5,6,7)) 

action.payload 只是第一个参数。我如何获得其他 6 个?

最佳答案

阅读相关documentation

By default, the generated action creators accept a single argument, which becomes action.payload. This requires the caller to construct the entire payload correctly and pass it in.

所以你可以调用 Action

dispatch(test([1,2,3,4,5,6,7])) 

这样,有效负载现在将成为您传递的数组。


但是,如果您需要能够使用多个参数调用它,您可以使用 prepare回调

If you want to add a meta or error property to your action, or customize the payload of your action, you have to use the prepare notation.

export const slice = createSlice({
name: 'reducer',
initialState: {

},
reducers: {
test: {
reducer(state, action){
console.log(action.payload) // 1
},
prepare(...arguments){
return {
payload: arguments;
}
}
}
},
});

这样,您调用操作的原始方式将再次产生一个数组的有效负载,该数组将包含您传递的所有参数,无论它们的数量如何。

关于reactjs - 具有多个参数的 redux 工具包 reducer ? redux 工具包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71778940/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com