安装

npm i history -S

定义

history.js文件

  1. import { createBrowserHistory } from "history";
  2. export default createBrowserHistory();

使用

app.js文件

  1. import React, { Component } from 'react';
  2. import { history, Navigation, NotFound } from './components';
  3. import { Switch, Route, Router, Redirect } from 'react-router-dom';
  4. import Main from './modules/main/views';
  5. import './App.css';
  6. const routes = [];
  7. export default class App extends Component {
  8. static addRoute(route) {
  9. if (route instanceof Array) {
  10. routes.push(...route);
  11. } else {
  12. routes.push(route);
  13. }
  14. }
  15. render() {
  16. return (
  17. <Navigation history={history} menuList={routes}>
  18. <Router history={history}>
  19. <Switch>
  20. <Route exact path='/main' component={Main} />
  21. <Redirect exact from='/' to='/main' />
  22. {
  23. routes.map(item => {
  24. if (item.children && item.children.length) {
  25. return item.children.map(it => <Route exact key={it.path} path={it.path} component={it.component} />);
  26. } else {
  27. return <Route exact key={item.path} path={item.path} component={item.component} />;
  28. }
  29. })
  30. }
  31. <Route component={NotFound} />
  32. </Switch>
  33. </Router>
  34. </Navigation>
  35. );
  36. }
  37. }

重定向

  1. import history from './history';
  2. this.props.history.push('/notFound');