我想用Apis传递道具
import {getAsyncComponent} from 'async-react-component';
const Apis = () => import(/* webpackChunkName: "apis" */ './app/components/Apis/Apis');
在render()方法中
return (
<BaseLayout>
<Switch>
<Redirect exact from="/" to="/apis"/>
<Route path={"/apis"} component={getAsyncComponent(Apis)}/>
<Route component={PageNotFound}/>
</Switch>
</BaseLayout>
);
答案 0 :(得分:0)
$ npm install babel-plugin-dynamic-import-webpack eslint-plugin-import eslint-import-resolver-webpack -D
或
$ yarn add babel-plugin-dynamic-import-webpack eslint-plugin-import eslint-import-resolver-webpack -D
webpack.config.js
resolve: {
alias: {
_root: path.resolve(__dirname, src),
},
},
.eslintrc
"settings": {
"import/resolver": "webpack",
"import/parser": "babel-eslint"
},
.babelrc
"plugins": [
"dynamic-import-webpack",
]
import React from 'react';
import PropTypes from 'prop-types';
const propTypes = {
path: PropTypes.string.isRequired,
};
class DynamicImport extends React.Component {
constructor(props) {
super(props);
this.load = this.load.bind(this);
this.state = {
Component: null,
};
this.load(props.path);
}
componentWillReceiveProps(nextProps) {
this.load(nextProps.path);
}
load(path) {
import(`_root/${path}`).then((module) => {
this.setState({ Component: module.default });
});
}
render() {
const { Component } = this.state;
if (Component) return <Component {...this.props} />;
return null;
}
}
DynamicImport.propTypes = propTypes;
export default DynamicImport;
return (
<BaseLayout>
<Switch>
<Redirect exact from="/" to="/apis"/>
<Route path="/apis" render={attr => <DynamicImport {...attr} path="app/components/Apis/Apis" />} />
<Route component={PageNotFound}/>
</Switch>
</BaseLayout>
);