我的redux todo应用程序中有这个选择器:
export const selectTodoSlice = (state) => state.todoReducer;
我必须以我在商店中定义减速器的相同方式命名这个state.todoReducer
:
import todoReducer from "../features/todo/todoSlice";
const store = configureStore({
reducer: {
todoReducer,
},
});
否则我会得到一些关于.map()
函数的错误。
所以我想知道这是否是一个惯例和规则,即选择器中返回函数的这一部分——state.todoReducer
——必须始终与您命名并传递到存储中的reducer相同?
当您将{ reducer: { todoReducer } }
传递给configureStore时,redux会在状态中创建相应的属性。
createStore({
reducer: {
todoReducer: (state, action) => { ... },
}
})
// redux state
{
todoReducer: {
// whatever todoReducer returns
}
}
对于reducer中的每个属性,您都会得到一个处于状态的属性:
createStore({
reducer: {
todoReducer: (state, action) => { ... },
someOtherReducer: (state, action) => { ... }
}
})
// redux state
{
todoReducer: {
// whatever todoReducer returns
},
someOtherReducer: {
// whatever someOtherReducer returns
}
}
选择器正在返回状态对象的命名属性。如果状态中不存在该命名属性,选择器将返回undefined。若后续代码期望一个数组,并试图在其上调用映射,则会出现错误。
考虑:
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