简体   繁体   English

使用多个参数调度并使用 Redux 工具包创建操作

[英]Dispatch with multiple parameters and create action with Redux Toolkit

I'm fairly new to Redux (and especially Redux Toolkit) and cannot wrap my head around the following issue.我是 Redux(尤其是 Redux 工具包)的新手,无法解决以下问题。

I'm rewriting old code with Toolkit.我正在使用 Toolkit 重写旧代码。

I understand that I can do the following in my createSlice.我知道我可以在我的 createSlice 中执行以下操作。

  reducers: {
    changeDay: (state, action) => {
      state.day = action.payload;
    }
}

and dispatch like this:并像这样发送:

  store.dispatch(changeDay(true));

Many scenarios in my application however take in second arguments, given the example from old redux without toolkit然而,我的应用程序中的许多场景都采用第二个 arguments,以没有工具包的旧 redux 为例

case ACTIVITY:
  return {
    activity: action.data.first,
    anotheractivity: action.data.second,
  };

The action for this looks as following:此操作如下所示:

function clickedActivity(first = undefined, second = undefined) {
  const data = {
    first,
    second,
  };
  return {
    type: ACTIVITY,
    data,
  };
}

In this case, I was able to call dispatch(clickedActivity(first,second)) and would get both values as desired.在这种情况下,我能够调用 dispatch(clickedActivity(first,second)) 并根据需要获得这两个值。

I assume that I have been looking for the wrong keywords in the documentation as I could not find a solution for this.我假设我一直在文档中寻找错误的关键字,因为我找不到解决方案。 Any hints?有什么提示吗?

You can pass an object in action.payload.您可以在 action.payload 中传递一个 object。 So for example,例如,

// assume you wanted to pass multiple parameters in reducer function changeDay

store.dispatch(changeDay({ type:ACTIVITY, data,}));


// Now inside the reducer, you can receive it like this

 reducers: {
    changeDay: (state, action) => {
      const {type,data}=action.payload; // You will receive the properties like this

    }
}


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

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