前言
實現通過單個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', }, }));