React通过dva-model-extend实现 dva 动态生成 model

前言

实现通过单个component 单个router通过相应的标识对应产生不同model实现数据包分离,model namespce将会覆盖基础的Model,其中的model[state|subscriptions|effects|reducers] 将通过Object.assign进行复制( Object.assign({},obj,obj1) )将源对象里面的属性添加到目标对象中去,若两者的属性名有冲突,后面的将会覆盖前面的。

背景

在子路由中动态导入model, 因为model比较大, 需要在这个子页面加载的时候加载model, 另外这个可以通过modelExtend 动态生成model(即动态生成namespace)

在原文中的定义

The model.namespace will be overrided by latter model.
model[state|subscriptions|effects|reducers] will be merged as Object.assign.
model.state will be overrided be latter model if it isn't an object.

实例

1、通过history中的location 传唯一标识实现区别生成唯一的model的namespace

imoport BaseModel from '../model/BaseModel'
import dynamic from 'dva/dynamic';// 通过dynamic实现动态加载路由、model
import modelExtend from 'dva-model-extend';
const dynamicWrapperCreateNewModel = (app, component, history) => dynamic({
app,
models: () => [modelExtend(BaseModel, { namespace: `createNewModel-${history.location.state.id}` })],
component,
});

2、在路由列表中添加路由

{
name: '路由',
path: 'BaseInstance',
component: dynamicWrapperCreateTab(app, () => import('../routes/OnlyRouter/BillBaseInstance'), history),
},

3、在UI中添加connect 生成器 连接动态生成的model

@connect(state => ({
myModel: state[`createNewModel-${history.state.state.id}`],
}))

4、通过React-Router4.0 跳转机制跳转到到路由

通过Link的方式传递id

import { Link } from 'dva/router';
<Link
to={{
pathname: this.props.path, // 传递path
state: { id: this.props.pathId }, 传递id 标识
}}
>

通过routerRedux的方式传递id

import { routerRedux } from 'dva/router';
yield put(routerRedux.replace({
pathname: '/dashboard/BaseInstance',
state: { // 标识
id: '0B64AF10-F1D0-6CD0-647F-160C50326F9D',
},
}));

  

原文地址:https://www.cnblogs.com/fuGuy/p/9089935.html