React-router app deployed on different locations (subdirectories)

浪子不回头ぞ 提交于 2020-01-05 04:06:07

问题


I have a react-router app that I have to deploy on different locations (subdirectories), so the basename would change. For example it should have the following paths:

/ (production)
/appname/env1
/appname/env2

I want to use Browser History, so I implemented the BrowserRouter from react-router, but I cannot pass to it a static basename. And obviously the routing won't work, for example if I don't pass any basename to BrowserRouter, if my homepage route is:

<Route path="/" exact component={MyComponent} />

it won't work when accessing to /appname/env1 or /appname/env2.

Is there a way to achieve what I am looking for with react-router?


回答1:


you can pass a base name like below

import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { useBasename } from 'history'
<Router history={useBasename(() => browserHistory)({ basename: BASENAME })}>

and you can set the basename maybe in your webpack configuration

 plugins: [
    new webpack.DefinePlugin({
      BASENAME: JSON.stringify("/appname/env1/")
    }),


来源:https://stackoverflow.com/questions/50250223/react-router-app-deployed-on-different-locations-subdirectories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!