使用React Router和Webpack Dev Server进行嵌套URL路由

10

我在使用react-router和webpack-dev-server实现嵌套的URL路由时遇到了一些问题。

webpack.config.js

output: {
    path: path.resolve(__dirname, 'build'),
    publicPath: "/", <-- this enabled routing to /register/step2
    filename: "js/bundle.js",
},

路由.js

const routes = {
    childRoutes: [
        { path: '/', component: Home },
        { path: '/login', component: Login },
        { path: '/register', component: Register },
        { path: '/register/step2', component: SecondStep },
    ]
};

export default (<Router routes={routes} history={createBrowserHistory()} />);
当我在应用程序中点击时,可以到达/register/step2,但是一旦我在浏览器中点击刷新,我的common.js和bundle.js都不见了:404,因为它试图从/register/目录加载所有内容。有人能帮忙吗?谢谢。
3个回答

8
我已经理解了。要启用此功能,需要两个东西。
webpack.config.js
devServer: {
    historyApiFallback: true <-- this needs to be set to true
}


routes.js

const routes = {
    childRoutes: [
        { path: '/', component: Home },
        { path: '/login', component: Login },
        { path: '/register', component: Register, childRoutes: [
            { path: 'step2', component: SecondStep },
        ] },
    ]
};

1
historyApiFallback: true,似乎解决了问题...谢谢。 - pravin
但不使用热重载:https://dev59.com/FZvga4cB1Zd3GeqP7c-g - Marc

0
请确保您的webpack配置文件包含以下代码:
output: {
    publicPath: '/'
},
devServer: {
    historyApiFallback: true
}

在本文中查看更多信息


-1
如果您使用hashHistory而不是createBrowserHistory(),它将防止服务器请求您当前服务器上的URL。
export default (<Router routes={routes} history={hashHistory} />);

有没有不使用哈希的方法来实现这个? - Bruce Lim
React-Router的指南建议使用browserHistory而不是hashHistory。https://github.com/reactjs/react-router/blob/1.0.x/docs/guides/basics/Histories.md#createbrowserhistory - Bruce Lim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接