我正在使用redux制作一个演示应用。我有 柜台 和 主题 减速器组合在一起,不幸的是,增量或减量动作调用主题减速器而不是计数器减速器。如果我只有一个reducer(没有组合),两个reducer都能正常工作。两个减速器是否共享它们的状态?好像增量动作会调用主题减速器的默认状态。
这里是 是我的代码。
在redux中,当你触发任何动作时,所有的reducer都会被调用,而每个reducer都会处理该动作。
当减速器不需要处理某个动作时,你需要返回原始状态。
这就是为什么一个 默认声明 在减速器中需要开关功能
现在在 themeReducer
你把状态初始化为一个主题对象,但随后的 CHANGE_THEME
动作,你更新状态,只存储名称,这打破了它的存储模式。
同时,作为默认情况,你将返回 state.name
属性,这意味着下一次减速器的状态就等于当前主题的名称。
解决方法是继续将所需的主题状态存储为一个对象,并在默认情况下。return state
现在,当你在settings.js中使用主题时,你可以使用 theme.name
reducerstheme.js
const themeReducer = (state = themes[0], action) => {
switch (action.type) {
case "CHANGE_THEME":
document.documentElement.style.setProperty(
"--primary-color",
themes[action.payload].colors.primary
);
document.documentElement.style.setProperty(
"--secondary-color",
themes[action.payload].colors.secondary
);
return themes[action.payload];
default:
document.documentElement.style.setProperty(
"--primary-color",
state.colors.primary
);
document.documentElement.style.setProperty(
"--secondary-color",
state.colors.secondary
);
return state;
}
};
export default themeReducer;
设置.js
function Settings() {
const counter = useSelector(state => state.counter);
const theme = useSelector(state => state.theme);
return (
<div>
<h2>This is the Settings page</h2>
<span>Counter: {counter}</span>
<br />
<span>Current theme: {theme.name}</span>
<Color />
</div>
);
}