使用反应路由器

时间:2018-04-04 15:05:37

标签: reactjs react-router react-redux router react-router-v4

我有异步组件,其中一切正常,但当我尝试传递path中的参数/ home /:id?时,它无法加载并给出错误 加载块失败。

请帮助我如何使用“react-router”正确传递参数:“^ 4.2.0”

<Switch>
 <Route path={`${match.url}home/:id?`} component={asyncComponent(() => 
     import('../containers/home'))}/>
 <Route path={`${match.url}dash`} exact component={asyncComponent(() => 
     import('../containers/dash'))}/>
</Switch>
  

async.js

 export default function asyncComponent(importComponent) {
class AsyncFunc extends Component {
    constructor(props) {
        super(props);
        this.state = {
            component: null
        };
    }

    componentWillMount() {
        Nprogress.start();
    }

    componentWillUnmount() {
        this.mounted = false;
    }

    async componentDidMount() {
        this.mounted = true;
        const {default: Component} = await importComponent();
        Nprogress.done();
        if (this.mounted) {
            this.setState({
                component: <Component {...this.props} />
            });
        }
    }

    render() {
        const Component = this.state.component || <div/>;
        return (
            <ReactPlaceholder type="text" rows={7} ready={Component !== 
    null}>
                {Component}
            </ReactPlaceholder>
        );
    }
}

 return AsyncFunc;
}

1 个答案:

答案 0 :(得分:0)

如果您在项目中使用webpack,下面的代码可能会对您有所帮助。

output: { filename: '[name].js', chunkFilename: 'js/[name].app.js', publicPath: '/' }

如您所见。只需更改chunkFilename和公共路径的目录即可。