在React中使用 react-router-dom 编程式路由导航的正确姿势【含V5.x、V6.x】

react-router-dom 编程式路由导航 (v5)

1.push跳转+携带params参数
 props.history.push(`/b/child1/${id}/${title}`);
2.push跳转+携带search参数
props.history.push(`/b/child1?id=${id}&title=${title}`);
3.push跳转+携带state参数
props.history.push(`/b/child1`, { id, title });
4.replace跳转+携带params参数
this.props.history.replace(`/home/message/detail/${id}/${title}`)
5.replace跳转+携带search参数
this.props.history.replace(`/home/message/detail?id=${id}&title=${title}`)
6.replace跳转+携带state参数
this.props.history.replace(`/home/message/detail`, { id, title });
7.前进
this.props.history.goForward();
8.回退
this.props.history.goForward();
9.前进或回退 ( go )
this.props.history.go(-2); //回退到前2条的路由
在一般组件中使用编程式路由导航 (非路由组件)
import {withRouter} from 'react-router-dom'

class Header extends Component {
    // withRouter(Header)后,就可以在一般组件内部使用 this.props.history 
    //...
}

export default withRouter(Header)

react-router-dom 编程式路由导航 (v6)

// v6版本编程导航使用 useNavigate (以下为引入代码)
import {  useNavigate } from "react-router-dom";
export default function A() {
  const navigate = useNavigate();
  //...
}
1.push跳转+携带params参数
 navigate(`/b/child1/${id}/${title}`);
2.push跳转+携带search参数
navigate(`/b/child2?id=${id}&title=${title}`);
3.push跳转+携带state参数
navigate("/b/child2", { state: { id, title }});
4.replace跳转+携带params参数
navigate(`/b/child1/${id}/${title}`,{replace: true});
5.replace跳转+携带search参数
navigate(`/b/child2?id=${id}&title=${title}`,{replace: true});
6.replace跳转+携带state参数
navigate("/b/child2", { state: { id, title },replace: true});

为您推荐相关文章:

  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值