关于react.js:在React中使用-reactrouterdom-编程式路由导航的正确姿势含V5xV6x

3次阅读

共计 1732 个字符,预计需要花费 5 分钟才能阅读完成。

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});

为您举荐相干文章:

  • 深度解析 React useRef Hook 的应用!https://juejin.cn/post/704258…
  • 最简洁的 Mbox 6.x 根本应用步骤介绍(仅三步)!!!https://juejin.cn/post/704110…
  • (干货) 全网最全 react-router-dom v6.0 学习指南(新个性深刻解读、继续更新 …)!!!https://juejin.cn/post/704028…
  • (原创)深刻解读 s React 中的 useState Hook 批改了值,然而不从新渲染,不刷新的问提 https://juejin.cn/post/703923…
  • React 中应用 react-router-dom 路由传参的三种形式详解【含 V5.x、V6.x】!!!https://juejin.cn/post/704284…
正文完
 0