简体   繁体   中英

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. How do I get the other 6?

Read the relevant 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.

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

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;
        }
      }
    }
  },
});

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. Single object parameter can be array or JSON object.

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

},

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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