在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});
© 版权声明
THE END
我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=270198dipw4ko
点赞9赞赏 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容