使用withRouter关联页面组件实现跳转刷新。
错误示例
import './Body.css';
import React, { lazy, Component, Suspense } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const Home = lazy(() => import('../Home'))
const About = lazy(() => import('../About'))
const User = lazy(() => import('../user/User'))
const Error = lazy(() => import('../Error'))
class Body extends Component {
// 配置路由规则 exact表示精确匹配,防止匹配其他页面的时候匹配到/,也就是首页
// Switch表示如果匹配到了路由,就不再往下面匹配了,如果不写Switch,则一直会匹配到404页面
render() {
return (
<div className="body">
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/user" component={User} />
<Route component={Error}></Route>
</Switch>
</Suspense>
</Router>
</div>
)
}
}
export default Body;
正确示例
import './Body.css';
import React, { lazy, Component, Suspense } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { withRouter } from 'react-router';
const Home = lazy(() => import('../Home'))
const About = lazy(() => import('../About'))
const User = lazy(() => import('../user/User'))
const Error = lazy(() => import('../Error'))
class Body extends Component {
// 配置路由规则 exact表示精确匹配,防止匹配其他页面的时候匹配到/,也就是首页
// Switch表示如果匹配到了路由,就不再往下面匹配了,如果不写Switch,则一直会匹配到404页面
render() {
return (
<div className="body" key={this.props.location.key}>
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/user" component={User} />
<Route component={Error}></Route>
</Switch>
</Suspense>
</Router>
</div>
)
}
}
export default withRouter(Body);
路由组件添加key,跳转识别。 这里的location有属性key。
withRouter是react-router的一个高阶组件,可获取history
render时会把match, location和history传入props
react中经过路由渲染的组件才拥有路由参数,使用this.props.history.push('/a')跳转到对应路由的页面
使用withRouter可以将路由参数传入this.props中
官方文档: You can get access to the history
object’s properties and the closest <Route>
's match
via the withRouter
higher-order component. withRouter
will pass updated match
, location
, and history
props to the wrapped component whenever it renders.