【问题标题】:Redux Selector function returns error if not named correctly如果命名不正确,Redux Selector 函数会返回错误
【发布时间】:2021-11-22 17:16:57
【问题描述】:

我的 redux todo 应用中有这个选择器:

export const selectTodoSlice = (state) => state.todoReducer;

我必须将其命名为 state.todoReducer,就像我在 store 中定义减速器一样:

import todoReducer from "../features/todo/todoSlice";
const store = configureStore({
  reducer: {
    todoReducer,
  },
});

...否则我会收到有关某些.map() 函数的错误。

所以我想知道这是否是一个约定和规则,即选择器中的这部分返回函数 — state.todoReducer — 必须始终与您命名并传递到您的商店的 reducer 相同?

【问题讨论】:

    标签: javascript reactjs redux react-redux redux-toolkit


    【解决方案1】:

    当你将{ reducer: { todoReducer } } 传递给configureStore 时,redux 会在state 中创建一个对应的属性。

    createStore({
      reducer: {
        todoReducer: (state, action) => { ... },
      }
    })
    
    // redux state
    {
      todoReducer: {
        // whatever todoReducer returns
      }
    }
    

    你会为 reducer 中的每个属性获得一个 state 属性:

    createStore({
      reducer: {
        todoReducer: (state, action) => { ... },
        someOtherReducer: (state, action) => { ... }
      }
    })
    
    // redux state
    {
      todoReducer: {
        // whatever todoReducer returns
      },
      someOtherReducer: {
        // whatever someOtherReducer returns
      }
    }
    

    您的选择器正在返回状态对象的命名属性。如果该命名属性在 state 中不存在,则选择器将返回 undefined。如果后续代码需要一个数组并尝试在其上调用 map,则会出现错误。

    考虑:

    const state = {
      todoReducer: ["one", "two", "three"]
    }
    
    // this works
    const todo = state.todoReducer; // array
    const allCaps = todo.map(item => item.toUpperCase());
    // ["ONE", "TWO", "THREE"]
    
    // this doesn't
    const notThere = state.nonexistentProperty; // undefined
    const boom = notThere.map(item => item.toUpperCase()); // error
    

    【讨论】:

    • 当我将其命名为其他名称时发生了同样的事情,例如状态.todo。它返回 undefined 并且只有在我将其重命名为与我命名为默认导出减速器相同的东西时才得到修复。所以为了避免这种情况,它总是必须与 store 中的默认 reducer 同名?
    • 用一些附加信息更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    相关资源
    最近更新 更多