我能在反应路由器中设置一个基本路由吗

假设我的应用程序的基本网址是 Example.com/app

是否可以在反应路由器中设置一个基本路由,而不是将所有路由写成

/app/a
/app/b
/app/c

我可以把它们指定为

a
b
c

我尝试了下面的例子,我发现在 医生但它不会工作(页面将显示任何东西)。也许是因为我使用了 response-router@3.0.0-alpha.1,或者我做错了什么。

import { useRouterHistory } from 'react-router'
import { createHistory } from 'history'


const history = useRouterHistory(createHistory)({
basename: '/app'
})


const Root = ({store}) => (
<Provider store={store}>
<Router history={history}>
<Route path='/' component={App}>
...
</Route>
</Router>
</Provider>
)
115162 次浏览

With the newest react router (v4) you can easily do this

<BrowserRouter basename="/calendar">
<Link to="/today"/> // renders <a href="/calendar/today">
</BrowserRouter>

If you want to use <Router />, that give you access to history object, allowing you to change page through history.push('/my-path') method directly from js. You will face the issue that BrowserRouter does not have history prop available, and Router does not have basename available.

The solution is the following:

const App: React.FC = () => {
// do not put a slash at the end of the basename value.
const history = createBrowserHistory({ basename: '/your-base-name' });


return <Router history={history}>
...
</Router>;
}

The base URL for all locations. If your app is served from a sub-directory on your server, you’ll want to set this to the sub-directory. A properly formatted basename should have a leading slash, but no trailing slash

https://reacttraining.com/react-router/web/api/BrowserRouter/basename-string