Skip to content

Commit

Permalink
refact: rewrite dynamic util, Close #1256
Browse files Browse the repository at this point in the history
  • Loading branch information
sorrycc committed Sep 29, 2017
1 parent 9539663 commit fa92d0a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
2 changes: 1 addition & 1 deletion packages/dva-example-user-dashboard/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,6 @@
"expect": "^1.20.2",
"husky": "^0.13.0",
"redbox-react": "^1.3.2",
"roadhog": "^1.2.0"
"roadhog": "^1.2.2"
}
}
38 changes: 37 additions & 1 deletion packages/dva/src/dynamic.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { asyncComponent } from 'react-async-component';
import React, { Component } from 'react';

const cached = {};
function registerModel(app, model) {
Expand All @@ -8,6 +8,42 @@ function registerModel(app, model) {
}
}

function asyncComponent(config) {
const { resolve } = config;

return class DynamicComponent extends Component {
constructor(...args) {
super(...args);
this.LoadingComponent =
config.LoadingComponent || (() => <p>loading...</p>);
this.load();
}

componentDidMount() {
this.mounted = true;
}

load() {
resolve().then(m => {
const AsyncComponent = m.default || m;
if (this.mounted) {
this.setState({ AsyncComponent });
} else {
this.state.AsyncComponent = AsyncComponent; // eslint-disable-line
}
});
}

render() {
const { AsyncComponent } = this.state;
const { LoadingComponent } = this;
if (AsyncComponent) return <AsyncComponent {...this.props} />;

return <LoadingComponent {...this.props} />;
}
};
}

export default function dynamic(config) {
const { app, models: resolveModels, component: resolveComponent } = config;
return asyncComponent({
Expand Down

0 comments on commit fa92d0a

Please sign in to comment.