app.model: namespace should be unique
dva-example-user-dashboard这个demo例子报错,页面第二次刷新时
报错信息如下: [HMR] inited with babel-plugin-dva-hmr VM327:27error Error: app.model: namespace should be unique at invariant (browser.js:40) at checkModel (createDva.js:448) at Object.injectModel (createDva.js:154) at registerModel (router.js:7) at router.js:28 at bootstrap d1c415e…:135 at Function.requireEnsure [as e] (bootstrap d1c415e…:596) at Function.ensure [as e] (bootstrap d1c415e…:133) at Object.getComponent (router.js:27) at getComponentsForRoute (getComponents.js:29) window.console.error @ VM327:27 newRender @ index.js:25 (anonymous) @ index.js:25 hotApply @ bootstrap d1c415e…:515 hotUpdateDownloaded @ bootstrap d1c415e…:323 hotAddUpdateChunk @ bootstrap d1c415e…:303 webpackHotUpdateCallback @ bootstrap d1c415e…:24 (anonymous) @ 2.d1c415e….hot-update.js:1 Navigated to http://localhost:8000/users users:7 Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:8000/index.css". index.js:25[HMR] inited with babel-plugin-dva-hmr
model 里定义的 namespace 有重复了,应该是要全局唯一的
dva-example-user-dashboar例子中,这个方法写得有问题
const cached = {};
function registerModel(app, model) {
if (!cached[model.namespace]) {
app.model(model);
cached[model.namespace] = 1;
}
}
修改成这样就可以
window.__cached_model__ = window.__cached_model__ || {};
function registerModel(app, model) {
if (!window.__cached_model__[model.namespace]) {
app.model(model);
window.__cached_model__[model.namespace] = 1;
}
}
const cached = {};
function registerModel(app, model) {
if (!cached[model.namespace]) {
app.model(model);
cached[model.namespace] = 1;
}
}
跟那例子一样的写法,没报错啊!
动态加载的时候重复加载路model会有这个问题,注意下
@longzhaobi 检查一下index.js中是不是require过这个model了,用dva g model这个命令创建model的话容易忽略这个问题
app.model(model);
cached[model.namespace] = 1;
After I swap this two line, it solved!
@adam1985 It save me.
若在全局中加载了某个model,在动态加载组件时,又去加载了该model,也是会报这个错,如下:
import personalModel from './models/personal';
app.model(personalModel);
<Route component={dynamic({models: () => ['personal']})} />