React Router v4 baseName 和自定义历史记录 [英] React Router v4 baseName and custom history
本文介绍了React Router v4 baseName 和自定义历史记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为我的路由分配一个基本名称,我可以使用 BrowserRouter.
不过,我还想指定自定义历史记录,以便以编程方式导航我的用户.我可以用路由器来做.
但是我不能,两者都做.是否可以扩展其中一个路由器以支持此功能或围绕它添加功能以添加此功能?
我目前的设置是这样 -
从'react'导入React;从'react-router-dom'导入{路由器,交换机,路由,重定向};从 './history' 导入 createHistory;从'./components/navigation/Navigation'导入导航;从 './components/private-route/PrivateRoute' 导入 PrivateRoute;从 './containers/home/Home' 导入 Home;从'./components/pageTwo/PageTwo'导入PageTwo;从'./components/callback/Callback'导入回调;从'./components/login/Login'导入登录;导出默认值 () =>(<路由器历史={createHistory}><div><导航/><开关><Route path="/callback" component={Callback}/><Route path="/login" component={Login}/><PrivateRoute path="/" 精确组件={Home}/><PrivateRoute path="/page-two" component={PageTwo}/><重定向到="/"/></开关>
</路由器>);
但是我很想实现诸如 -
解决方案
<应用程序/></BrowserRouter>
或者直接配置history
对象:
import { Router } from 'react-router';从'history/createBrowserHistory'导入createBrowserHistory;const history = createBrowserHistory({ basename: '/your/app' });<路由器历史={历史}><应用程序/></路由器>
I would like to assign a basename to my routes, which I can with BrowserRouter.
I would also however like to specify a custom history so I can programatically navigate my users. Which I can do, with Router.
I can't however, do both. Is it possible to extend one of the routers to support this or wrap function round it to add this?
My current setup is this -
import React from 'react';
import { Router, Switch, Route, Redirect } from 'react-router-dom';
import createHistory from './history';
import Navigation from './components/navigation/Navigation';
import PrivateRoute from './components/private-route/PrivateRoute';
import Home from './containers/home/Home';
import PageTwo from './components/pageTwo/PageTwo';
import Callback from './components/callback/Callback';
import Login from './components/login/Login';
export default () => (
<Router history={createHistory}>
<div>
<Navigation />
<Switch>
<Route path="/callback" component={Callback} />
<Route path="/login" component={Login} />
<PrivateRoute path="/" exact component={Home} />
<PrivateRoute path="/page-two" component={PageTwo} />
<Redirect to="/" />
</Switch>
</div>
</Router>
);
However I'd love to achieve something such as -
<Router history={createHistory} basename="foo">
解决方案
<BrowserRouter basename="/your/app">
<App/>
</BrowserRouter>
Or to directly configure the history
object:
import { Router } from 'react-router';
import createBrowserHistory from 'history/createBrowserHistory';
const history = createBrowserHistory({ basename: '/your/app' });
<Router history={history}>
<App />
</Router>
这篇关于React Router v4 baseName 和自定义历史记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文