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

为您推荐相关文章:

posted @ 2021-12-18 09:49  JasonMa丶丶  阅读(977)  评论(4编辑  收藏  举报