gpt4 book ai didi

reactjs - React/redux,显示多个组件,共享相同的操作,但具有不同的状态

转载 作者:行者123 更新时间:2023-12-03 13:19:02 24 4
gpt4 key购买 nike

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

向导状态由 redux/actions 驱动。当一个 Action 被触发时,我使用一个 reducer 来更新我的状态。

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

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

这是推荐的吗?有没有可以让这变得更容易的库?

最佳答案

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

作为数组

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

您可以编写一个向导缩减程序,它了解如何缩减单个向导状态。

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

然后编写一个 wizardsReducer 来了解如何减少向导列表。

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

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

combineReducers({
wizards: wizardsReducer
});

作为对象

如果您将向导存储在对象中,则必须以稍微不同的方式构建 wizardsReducer

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

当我们可以立即选择我们需要的状态时,映射状态没有多大意义。

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

关于reactjs - React/redux,显示多个组件,共享相同的操作,但具有不同的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36303028/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com