React Router v4 baseName 和自定义历史记录

IT技术 reactjs react-router react-redux
2021-04-27 15:17:13

我想为我的路由分配一个基本名称,我可以使用 BrowserRouter。

然而,我还想指定一个自定义历史记录,以便我可以以编程方式导航我的用户。我可以用路由器来做。

但是,我不能,两者都做。是否可以扩展其中一个路由器以支持此功能或围绕它添加功能以添加此功能?

我目前的设置是这样的 -

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

但是我很想实现诸如-

<Router history={createHistory} basename="foo">
1个回答

你可以

<BrowserRouter basename="/your/app">
  <App/>
</BrowserRouter>

或者直接配置history对象:

import { Router } from 'react-router';
import createBrowserHistory from 'history/createBrowserHistory';

const history = createBrowserHistory({ basename: '/your/app' });

<Router history={history}>
  <App />
</Router>