Is it possible to define default route in react-router?
P粉128563140
2023-08-27 17:06:31
<p>Suppose my app's base URL is <em>example.com/app</em></p>
<p>Is it possible to set up basic routing in react-router instead of writing all routes as </p>
<pre class="brush:php;toolbar:false;">/app/a
/app/b
/app/c</pre>
<p>I can specify them as </p>
<pre class="brush:php;toolbar:false;">a
b
c</pre>
<p>I tried the following example found in the documentation but it doesn't work (the page won't display anything). Maybe it's because I'm using react-router@3.0.0-alpha.1 or I'm doing something wrong. </p>
<pre class="brush:php;toolbar:false;">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>
)</pre>
<p><br /></p>
If you want to use
, it gives you access to the history object, allowing you to change the page viahistory.push('/my-path')
code> directly Method from js. You will face the problem that BrowserRouter has nohistory
property available, and Router has nobasename
available.The solution is as follows:
https://reacttraining.com/react-router/web/ api/BrowserRouter/basename-string
Using the latest react router (v4) you can do this easily