美文网首页
在React中使用 react-router-dom 编程式路由

在React中使用 react-router-dom 编程式路由

作者: JasonMa丶 | 来源:发表于2021-12-21 09:11 被阅读0次

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中使用 react-router-dom 编程式路由

      本文链接:https://www.haomeiwen.com/subject/nftgfrtx.html