简体   繁体   English

具有多个参数的redux工具包减速器? 还原工具包

[英]redux toolkit reducer with multiple parameters? redux toolkit

Given this鉴于这种

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

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

    },

})

then I run this然后我运行这个

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

action.payload is only the 1st parameter. action.payload只是第一个参数。 How do I get the other 6?我如何获得其他6个?

Read the relevant documentation阅读相关文档

By default, the generated action creators accept a single argument, which becomes action.payload .默认情况下,生成的动作创建者接受一个参数,即action.payload This requires the caller to construct the entire payload correctly and pass it in.这需要调用者正确构造整个有效载荷并将其传入。

So you could do call the action with所以你可以用

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

this way, the payload will now be the array you passed.这样,有效负载现在将是您传递的数组。


If, however, you need to be able to call it with multiple arguments, you can use the prepare callback但是,如果您需要能够使用多个参数调用它,则可以使用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.如果您想为您的操作添加metaerror属性,或自定义您的操作的payload ,您必须使用prepare符号。

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

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

This way, your original way of calling the action will again result in a payload of an array which will contain all the arguments you passed, regardless of their number.这样,您调用操作的原始方式将再次产生一个数组的有效负载,该数组将包含您传递的所有参数,无论它们的数量如何。

Yes, We can send multiple parameters in redux reducer but after wrapping inside single object.是的,我们可以在 redux reducer 中发送多个参数,但是在包装到单个对象之后。 Single object parameter can be array or JSON object.单个对象参数可以是数组或 JSON 对象。

// as an array
dispatch(test(["first","second","third"]));
// as a JSON object
dispatch(test({ first:1, second:2, third:3 }));

your result will be like this.你的结果会是这样的。

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 }
   } 

},

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM