這實際上是一個相當晦澀的問題。究其原因是因爲,每the Redux documentation on createStore
:
When a store is created, Redux dispatches a dummy action to your reducer to populate the store with the initial state. You are not meant to handle the dummy action directly. Just remember that your reducer should return some kind of initial state if the state given to it as the first argument is undefined, and you're all set.
而且通過文檔提到的只是讓這個假動作恰好be this line the source:
dispatch({ type: ActionTypes.INIT })
這裏,ActionTypes.INIT
基本上是跟着一個隨機字符串,字符串@@redux/INIT
數字和句點。
因此,當你與createStore
創建存儲,虛擬動作被分派到你的減速,和動作類型在reducers
對象不存在,所以你得到的錯誤,undefined是不是一個函數。這就是爲什麼你總是有你的減速機默認情況下。例如,與switch語句,你總是返回狀態的默認情況下:
switch(action.type) {
…
default:
return state;
}
默認情況下允許的動作捕捉如終極版本身派出誘敵動作。同樣的原則也適用於你的代碼:
export default (state = initialState, action) => reducers[action.type] ? reducers[action.type](state)(action.payload) : state;
這種檢查是否減速的reducers
對象實際存在。如果是這樣,它會調用減速器。如果不是,就像在默認情況下一樣,只是返回狀態。
看起來它可以基於顯示的內容工作。在發生錯誤的地方記錄'redurs'的值是多少? – bazzells
@bazzells Nope,Redux在商店創建時分派一個虛擬動作,OP不處理錯誤。查看我的答案瞭解更多詳情。 – Li357