实战 react-redux 在vite 中的应用

关键点
  1. 多个reducer 如何统一导出
  2. 如何在dispatch时 指定对应的reducer
  3. 如何在每个 reducer 中初始化自己的state.
项目git

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;

在react组件中使用redux
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);

目前存在的问题
  1. 在reducer中异步请求如何更新state
  2. …其他问题后续补充
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值