背景
每次添加一个新的redcuer时,需要手动添加到combineReducers,非常麻烦,又没有一种方法可以自动导入呢?
Vite的import.meta.glob
具体用法参考import.meta.glob
目录结构
文件内容
global和home基本一致
index.js
import { backObj } from "@/utils/index";
import { homeState } from "./state"
export const UPDATA_STORE = Symbol("STORE_UPDATA")
export default (state = homeState, action) => {
switch (action.type) {
case UPDATA_STORE: {
const payload = backObj(action.payload);
return { ...state, ...payload };
}
default:
return state
}
}
export { action as homeAction } from "./action"
action.js
import { UPDATA_STORE } from "./index"
export const action = {
updateStore: (payload) => dispatch => {
dispatch({
type: UPDATA_STORE,
payload
})
}
}
state.js
import { menuData } from "@/config/sideMenu"
export const homeState = {
sideMenu: menuData
}
store下的index.js
import { createStore, combineReducers, applyMiddleware } from "redux"
import { thunk } from 'redux-thunk'
const reducerModules = import.meta.glob('./**/index.js', { eager: true })
const reducers = {}
for (const key in reducerModules) {
const name = key.split('/')[1]
reducers[name] = reducerModules[key].default
}
export default createStore(combineReducers(reducers), applyMiddleware(thunk))