当使用 combineReducers 时,Action 调用了错误的减速器。

问题描述 投票:0回答:2

我正在使用redux制作一个演示应用。我有 柜台主题 减速器组合在一起,不幸的是,增量或减量动作调用主题减速器而不是计数器减速器。如果我只有一个reducer(没有组合),两个reducer都能正常工作。两个减速器是否共享它们的状态?好像增量动作会调用主题减速器的默认状态。

这里是 是我的代码。

reactjs redux react-redux
2个回答
0
投票

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

工作演示


0
投票

给动作类型分别命名,就可以了!

更多讨论请看这个答案。Redux中的Actions应该总是唯一的吗?

另外,你似乎有一个主题还原器的bug,这可能也是一些无法解释的行为的原因。

© www.soinside.com 2019 - 2024. All rights reserved.