React route不刷新

使用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 matchlocation, and history props to the wrapped component whenever it renders.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值