是否可以在react-router中定义默认路由?
P粉128563140
P粉128563140 2023-08-27 17:06:31
0
2
428
<p>假设我的应用的基本网址是 <em>example.com/app</em></p> <p>是否可以在react-router中设置基本路由,而不是将所有路由写为</p> <pre class="brush:php;toolbar:false;">/app/a /app/b /app/c</pre> <p>我可以将它们指定为</p> <pre class="brush:php;toolbar:false;">a b c</pre> <p>我尝试了在文档中找到的以下示例,但它不起作用(页面不会显示任何内容)。也许是因为我使用的是react-router@3.0.0-alpha.1,或者我做错了什么。 </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>
P粉128563140
P粉128563140

全部回复(2)
P粉087074897

如果您想使用,它可以让您访问历史对象,允许您通过history.push('/my-path')更改页面 code>直接来自js的方法。您将面临这样的问题:BrowserRouter 没有可用的 history 属性,并且 Router 没有可用的 basename

解决办法如下:

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>;
}

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

P粉647449444

使用最新的react router (v4),你可以轻松做到这一点

<BrowserRouter basename="/calendar">
  <Link to="/today"/> // renders <a href="/calendar/today">
</BrowserRouter>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!