React經過dva-model-extend實現 dva 動態生成 model

前言

實現經過單個component 單個router經過相應的標識對應產生不一樣model實現數據包分離,model namespce將會覆蓋基礎的Model,其中的model[state|subscriptions|effects|reducers] 將經過Object.assign進行復制( Object.assign({},obj,obj1) )將源對象裏面的屬性添加到目標對象中去,若二者的屬性名有衝突,後面的將會覆蓋前面的。javascript

背景

在子路由中動態導入model, 由於model比較大, 須要在這個子頁面加載的時候加載model, 另外這個能夠經過modelExtend 動態生成model(即動態生成namespace)java

在原文中的定義app

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.ide

實例

一、經過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,
});

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

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

三、在UI中添加connect 生成器 鏈接動態生成的model

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

四、經過React-Router4.0 跳起色制跳轉到到路由

經過Link的方式傳遞idthis

import { Link } from 'dva/router';
<Link
to={{
pathname: this.props.path, // 傳遞path
state: { id: this.props.pathId }, 傳遞id 標識
}}
>

經過routerRedux的方式傳遞idspa

import { routerRedux } from 'dva/router';
yield put(routerRedux.replace({
pathname: '/dashboard/BaseInstance',
state: { // 標識
id: '0B64AF10-F1D0-6CD0-647F-160C50326F9D',
},
}));
相關文章
相關標籤/搜索