【问题标题】:loading async component with parameter in react router在反应路由器中加载带有参数的异步组件
【发布时间】:2018-09-14 05:15:08
【问题描述】:

我有异步组件,一切正常,但是当我尝试在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;
}

【问题讨论】:

  • 为什么要添加“?”在':id'之后?
  • @nirit-levi 它可能是任何可选的东西,所以

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


【解决方案1】:

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

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

如你所见。它只是更改 chunkFilename 的目录和公共路径。

【讨论】:

    猜你喜欢
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 2019-01-05
    • 2016-09-15
    相关资源
    最近更新 更多