安装
npm i history -S
定义
history.js文件
import { createBrowserHistory } from "history";
export default createBrowserHistory();
使用
app.js文件
import React, { Component } from 'react';
import { history, Navigation, NotFound } from './components';
import { Switch, Route, Router, Redirect } from 'react-router-dom';
import Main from './modules/main/views';
import './App.css';
const routes = [];
export default class App extends Component {
static addRoute(route) {
if (route instanceof Array) {
routes.push(...route);
} else {
routes.push(route);
}
}
render() {
return (
<Navigation history={history} menuList={routes}>
<Router history={history}>
<Switch>
<Route exact path='/main' component={Main} />
<Redirect exact from='/' to='/main' />
{
routes.map(item => {
if (item.children && item.children.length) {
return item.children.map(it => <Route exact key={it.path} path={it.path} component={it.component} />);
} else {
return <Route exact key={item.path} path={item.path} component={item.component} />;
}
})
}
<Route component={NotFound} />
</Switch>
</Router>
</Navigation>
);
}
}
重定向
import history from './history';
this.props.history.push('/notFound');