我的 redux todo 應用中有這個選擇器:
export const selectTodoSlice = (state) => state.todoReducer;
我必須以state.todoReducer與我在商店中定義減速器相同的方式命名它:
import todoReducer from "../features/todo/todoSlice";
const store = configureStore({
reducer: {
todoReducer,
},
});
...否則我會得到有關某些.map()功能的錯誤。
所以我想知道這是否是一個約定和規則,即選擇器中回傳函式的這一部分state.todoReducer必須始終與您命名并傳遞到您的商店的減速器相同?
uj5u.com熱心網友回復:
當你傳遞{ 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/363234.html
標籤:javascript 反应 还原 反应还原 redux-工具包
上一篇:在頁面加載后反應添加路由
