https://github.com/zsz91/vite-react 欢迎fork
store.ts
import { createStore,combineReducers } from 'redux';
import reducers from '../reducer';
export default createStore(reducers);
reducer.ts // 获取所有的reducer 并返回给store
const models = import.meta.globEager('./*.ts');
// 读取所有的reducer文件 基于vite2.0的功能
// https://cn.vitejs.dev/guide/features.html#glob-import
for(let item in models){
const newKey = models[item].default.namespace;
models[newKey] = models[item].default;
delete models[item];
}
export default function reducer(state = {}, action) {
if(!action?.type || action.type.indexOf(`/`) === -1){
throw new Error('没有正确的type');
}
const type = action.type.split('/'); //
const modelName: string = type[0];
const model: object = models[modelName]; //对应的model
const initState: object = {};
for(let item in models){
initState[item] = models[item].state || {}; // 获取所有的state
}
if(!model){
return initState;
// 没有找到对应的model 直接返回state
}
initState[modelName] = model[type[1]](action);
// 执行 action 方法 更新对应model 的state
return initState;
}
test2.ts // 声明一个reducer
const test2 = {
namespace: 'test2',
state: {
name: '我是这个囤里土生土长的人',
}, // 初始值
changeName: function(payload){
// console.log(payload);
return {
...this.state,
name: payload?.name + Math.random(),
};
},
}
export default test2;
import React from "react";
import { connect } from "react-redux";
import { Button } from "antd";
function Head(props) {
const { name, dispatch } = props;
console.log(name, "Head 重新render了");
console.log(props);
const addState = () => {
dispatch({ // dispath action
type: "test2/changeName",
// 通过 "/" 区分 是哪个reducer 以及 action type
name: "我的老家就住在这个囤, 我是这个囤里土生土长的人",
// 新的state
});
};
return (
<div>
redux-state 我是来自reducer的name: === {name}
<Button onClick={addState}>123</Button>
</div>
);
}
export default connect(({ test2 }) => {
return test2;
})(Head);