React route不刷新

博客介绍了在React中使用withRouter关联页面组件实现跳转刷新的方法。withRouter是react-router的高阶组件,可获取history,将路由参数传入props。还给出错误与正确示例,提到路由组件添加key可实现跳转识别,经路由渲染的组件才有路由参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用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.

### 配置React路由防止页面刷新时数据丢失 在React应用程序中,通过合理配置`react-router-dom`并结合其他技术手段能够有效避免因页面刷新而导致的数据丢失问题。以下是几种可行的方法: #### 方法一:利用URL参数保存必要信息 将重要参数编码至URL路径或查询字符串中是一种简单而有效的策略[^4]。这种方式仅使得用户可以直接分享带有特定上下文的链接,而且浏览器默认会在地址栏保留这些信息,即使发生刷新操作。 对于动态部分的内容,比如文章ID、商品编号等,应该优先考虑将其作为URL的一部分来处理。这可以通过定义带占位符的Route来进行设置: ```jsx <Route path="/item/:id" component={ItemDetail} /> ``` 在目标组件内部则可通过`useParams()`钩子轻松读取所需参数值: ```javascript import { useParams } from 'react-router-dom'; function ItemDetail() { const { id } = useParams(); // 使用id执行相应逻辑... } ``` #### 方法二:借助Session Storage持久化关键状态 除了依赖于URL外,还可以利用Web Storage API中的`sessionStorage`对象临时存储一些易频繁变动的状态信息[^5]。这种方法特别适用于那些适合暴露在URL里的敏感数据或是体积较大的JSON结构体。 具体做法是在导航前立即将待传输的信息写入`sessionStorage`;到达新页面后尝试从中恢复之前记录下来的内容。需要注意的是,由于`sessionStorage`仅限同源访问且生命周期绑定于单次会话,因此非常适合用来应对本案例描述的情况——即希望保持一定范围内的一致性而影响全局环境或其他标签页的行为模式。 下面是一个简单的例子展示如何在两个同组件间安全地交换数据的同时确保刷新影响现有视图呈现效果: **Component A (Sender):** ```javascript // 假设这里有一个名为'userId'的重要字段需要传递给下一个页面 const userId = "some-user-id"; window.sessionStorage.setItem('sharedUserId', JSON.stringify(userId)); history.push('/target-page'); ``` **Component B (Receiver):** ```javascript componentDidMount(){ try{ const storedId = window.sessionStorage.getItem('sharedUserId'); if(storedId){ this.setState({ userId: JSON.parse(storedId), }); } }catch(e){} } render(){ return ( <div> {/* 渲染基于this.state.userId的结果 */} </div> ); } ``` #### 方法三:引入第三方库增强用户体验连续性 考虑到更复杂的交互需求以及更好的性能表现,有时单纯依靠上述基础方案可能足以满足实际项目的要求。此时可以评估是否有必要引入专门设计用于改善SPA(Single Page Application)体验流畅度的工具包,例如提到过的`react-activation`插件[^2]。这类解决方案往往提供了更加优雅的方式去控制组件实例的生命期,从而减少必要的重新渲染次数,并允许开发者自定义何时何地触发更新动作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值