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

图片[1]-在React中使用react-router-dom编程式路由导航【含V5.x、V6.x】-不念博客
react

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: <strong>true</strong>});

5.replace跳转+携带search参数

navigate(`/b/child2?id=${id}&title=${title}`,{replace: <strong>true</strong>});

6.replace跳转+携带state参数

navigate("/b/child2", { state: { id, title },replace: <strong>true</strong>});
© 版权声明
THE END
喜欢就支持一下吧
点赞84赞赏 分享
评论 抢沙发
头像
欢迎光临不念博客,留下您的想法和建议,祝您有愉快的一天~
提交
头像

昵称

取消
昵称代码图片

    暂无评论内容