React类组件中替代window.location.replace的react-router-dom无刷新跳转方法
React类式组件中react-router-dom无刷新跳转实现
先看你原来的跳转代码:
if (data.success === true) { window.location.replace('/verify') }
下面分react-router-dom的两个主要版本给出等价实现:
v5版本实现
在react-router-dom v5里,类组件可以直接通过props.history完成无刷新跳转,其中replace方法和你原代码的window.location.replace行为完全一致:
// 类组件内部的处理逻辑 if (data.success === true) { this.props.history.replace('/verify'); }
注意:你的类组件必须是被Route组件直接渲染的,或者用withRouter高阶组件包裹,才能拿到history这个props。
v6版本实现
react-router-dom v6移除了withRouter,也不再自动给类组件注入路由相关props,这时候需要自己封装一个高阶组件,把useNavigate的能力传递给类组件:
- 先写一个封装用的高阶组件:
import { useNavigate } from 'react-router-dom'; const withNavigate = (Component) => { return (props) => { const navigate = useNavigate(); return <Component {...props} navigate={navigate} />; }; };
- 给你的类组件套上这个高阶组件,然后在组件内使用:
import React from 'react'; class YourComponent extends React.Component { handleDataCheck = (data) => { if (data.success === true) { // 用navigate的replace模式,对应原代码的replace行为 this.props.navigate('/verify', { replace: true }); } }; // 其他组件逻辑... } export default withNavigate(YourComponent);
如果不需要replace模式(想保留当前页面的历史记录),可以去掉第二个参数,直接写this.props.navigate('/verify')。
内容的提问来源于stack exchange,提问作者happy_buddy
相关产品推荐
相关产品推荐

