如何在React Route中使用getAsyncComponent传递道具

时间:2017-11-24 05:04:21

标签: reactjs react-router

我想用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>
);

1 个答案:

答案 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

webpack.config.js

resolve: {
  alias: {
    _root: path.resolve(__dirname, src),
  },
},

eslint

.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>
);