当前位置: 首页 > 工具软件 > astore > 使用案例 >

React: Reducer 的分离与合并 遇到的问题报错‘store.getState is not a function‘

薄哲
2023-12-01

分离: 将reducer部分分类管理,防止reducer函数冗长;

合并: 用redux中的combineReducers将分离的各个reducer整合在store下的index文件夹中

示例:

src/store/reducer/book.js

export default function book (state = ['三国演义', '水浒传'], action) {
  console.log(action)
  switch (action.type) {
    case 'book/add':
      return [state, action.payload]
    default:
      return state
  }
}

src/store/index

import book from './reducer/book'
import user from './reducer/user'

import { combineReducers, createStore } from 'redux'

const rootReducer = combineReducers({
  book,
  user
})

export default createStore(rootReducer)

千万不要像我一样忘记在合并reducers时使用createStore(),否则导致的报错会是'store.getState is not a function'

(createStore: 创建整个redux的核心部分store.)

 类似资料: