使用react-router和webpack dev服务器的嵌套url路由

Bru*_*Lim 8 reactjs webpack react-router webpack-dev-server

我在使用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",
},
Run Code Online (Sandbox Code Playgroud)

routes.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()} />);
Run Code Online (Sandbox Code Playgroud)

当在appliation中点击时,我可以进入/ register/step2,但是一旦我在浏览器中点击刷新,我的common.js和bundle.js就丢失了:404,因为它试图从/ register /目录加载所有东西.

有人可以帮忙吗?谢谢.

Bru*_*Lim 9

我想到了.启用此功能需要2件事.

webpack.config.js

devServer: {
    historyApiFallback: true <-- this needs to be set to true
}
Run Code Online (Sandbox Code Playgroud)


routes.js

const routes = {
    childRoutes: [
        { path: '/', component: Home },
        { path: '/login', component: Login },
        { path: '/register', component: Register, childRoutes: [
            { path: 'step2', component: SecondStep },
        ] },
    ]
};
Run Code Online (Sandbox Code Playgroud)


Ric*_*chG -1

如果您使用 hashHistory 而不是 createBrowserHistory() ,它将阻止服务器请求您服务器上的当前 url。

export default (<Router routes={routes} history={hashHistory} />);
Run Code Online (Sandbox Code Playgroud)