我正在使用 redux 开发一个演示应用程序。我有计数器和主题减速器组合,不幸的是增量或减量动作调用主题减速器而不是计数器减速器。如果我只有一个减速器(未组合),两个减速器都可以正常工作。两个减速器是否共享它们的状态?似乎增量操作调用主题减速器的默认状态。
这是我的代码。
我正在使用 redux 开发一个演示应用程序。我有计数器和主题减速器组合,不幸的是增量或减量动作调用主题减速器而不是计数器减速器。如果我只有一个减速器(未组合),两个减速器都可以正常工作。两个减速器是否共享它们的状态?似乎增量操作调用主题减速器的默认状态。
这是我的代码。
使用 redux,当您触发任何操作时,所有 reducer 都会使用该特定操作调用,并且由每个 reducer 来处理该操作。
当 reducer 不需要处理某个动作时,您需要返回原始状态
这就是为什么需要 reducer switch 函数中的default 语句的原因
现在themeReducer,您将状态初始化为主题对象,但随后CHANGE_THEME您更新状态以仅存储破坏其存储模式的名称
同样作为默认值,您将返回该state.name属性,这意味着下次减速器的状态等于当前主题的名称
解决方案是继续存储所需的主题状态为对象,默认情况下return state
现在在 settings.js 中使用主题时,您可以使用theme.name
减速器/theme.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>
);
}