React Router v4 baseName and custom history

2020-06-11 13:40发布

问题:

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">

回答1:

You can:

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