具有多个参数的 redux 工具包减速器? redux 工具包
redux toolkit reducer with multiple parameters? redux toolkit
鉴于此
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.
所以你可以用
调用动作
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;
}
}
}
},
});
这样,您调用操作的原始方式将再次产生一个数组的有效负载,该数组将包含您传递的所有参数,无论它们的数量如何。
是的,我们可以在 redux reducer 中发送多个参数,但是在包装在单个对象中之后。单个对象参数可以是数组或JSON对象。
// as an array
dispatch(test(["first","second","third"]));
// as a JSON object
dispatch(test({ first:1, second:2, third:3 }));
你的结果会是这样的。
export const slice = createSlice({
name: 'reducer',
initialState: {
},
reducers: {
test: (state, action) => {
console.log(action.payload) // ["first","second","third"]
// or in case of JSON object
console.log(action.payload) // { first:1, second:2, third:3 }
}
},
})
鉴于此
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.
所以你可以用
调用动作dispatch(test([1,2,3,4,5,6,7]))
这样,有效负载现在就是您传递的数组。
但是,如果您需要能够使用多个参数调用它,则可以使用 prepare
回调
If you want to add a
meta
orerror
property to your action, or customize thepayload
of your action, you have to use theprepare
notation.
export const slice = createSlice({
name: 'reducer',
initialState: {
},
reducers: {
test: {
reducer(state, action){
console.log(action.payload) // 1
},
prepare(...arguments){
return {
payload: arguments;
}
}
}
},
});
这样,您调用操作的原始方式将再次产生一个数组的有效负载,该数组将包含您传递的所有参数,无论它们的数量如何。
是的,我们可以在 redux reducer 中发送多个参数,但是在包装在单个对象中之后。单个对象参数可以是数组或JSON对象。
// as an array
dispatch(test(["first","second","third"]));
// as a JSON object
dispatch(test({ first:1, second:2, third:3 }));
你的结果会是这样的。
export const slice = createSlice({
name: 'reducer',
initialState: {
},
reducers: {
test: (state, action) => {
console.log(action.payload) // ["first","second","third"]
// or in case of JSON object
console.log(action.payload) // { first:1, second:2, third:3 }
}
},
})