React/redux,显示多个组件,共享相同的动作,但具有不同的状态 [英] React/redux, displaying multiple components, sharing same actions, but with different state

查看:44
本文介绍了React/redux,显示多个组件,共享相同的动作,但具有不同的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个可重复使用的容器.这是一个有多个页面的向导.

Let's say I have a reusable container. It is a wizard with multiple pages.

向导状态由 redux/actions 驱动.当一个动作被触发时,我使用一个减速器来更新我的状态.

The wizard state is driven by redux/actions. When an action is fired, I use a reducer to update my state.

如果我想复制多个向导并拥有自己的状态怎么办?

What if I want to have multiple wizards duplicated, with it's own state?

我认为必须有一种方法让某个动态 reducer(可以创建/销毁)处理操作,然后让每个单独的向导从存储/状态的这些动态部分驱动.

I am thinking there must be a way to have actions handled by a certain dynamic reducer (that can be created/destroyed), and then have each individual wizard driven from these dynamic pieces of the store/state.

这是推荐的吗?有哪些库可以让这件事变得更容易?

Is this recommended? Are the libraries out there that make this easier?

推荐答案

只需将您的主状态划分为您需要的多个向导状态,并随每个操作发送一个向导 id,以便您的 reducer 知道要处理哪个.

Just partition your main state into as many wizard states as you need and send a wizard id along with each action so that your reducer knows which one to tackle.

{
  wizards: [
    { id: 'A', state: true },
    { id: 'B', state: false },
    { id: 'C', state: true }
  ]
}

您可以编写一个向导 reducer,它了解如何减少单个向导状态.

You can write a wizard reducer which understands how to reduce a single wizard state.

function wizardReducer(wizard, action) {
  switch(action) {
    case 'TOGGLE':
      return {
        id: wizard.id,
        state: !wizard.state
      };
    default:
      return wizard;
  }
}

然后编写一个wizardsReducer,它了解如何减少向导列表.

Then write a wizardsReducer which understands how to reduce a list of wizards.

function wizardsReducer(wizards, action) {
  return wizards.map(function(wizard) {
    if(action.id == wizard.id) {
      return wizardReducer(wizard, action);
    } else {
      return wizard;
    }
  });
}

最后,使用 combineReducers 创建一个根 reducer,它将 wizards 属性的责任委托给这个 wizardsReducer.

Finally, use combineReducers to create a root reducer which delegates responsibility for the wizards property to this wizardsReducer.

combineReducers({
  wizards: wizardsReducer
});

作为对象

如果您将向导存储在一个对象中,则必须稍微不同地构建您的 wizardsReducer.

{
  wizards: {
    A: { id: 'A', state: true },
    B: { id: 'B', state: false },
    C: { id: 'C', state: true }
  }
}

当我们可以直接选择我们需要的状态时,映射状态没有多大意义.

It wouldn't make much sense to map over the states, when we can just select the state we need straight away.

function wizardsReducer(wizards, action) {
  if(!(action.id in wizards)) return wizards;

  const wizard = wizards[action.id];
  const updatedWizard = wizardReducer(wizard, action);

  return {
    ...wizards,
    [action.id]: updatedWizard
  };
}

这篇关于React/redux,显示多个组件,共享相同的动作,但具有不同的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆