【问题标题】:How to go back to previous route in react-router-dom v6如何在 react-router-dom v6 中返回上一条路线
【发布时间】:2021-05-03 00:43:50
【问题描述】:

在早期版本中,我们可以使用 history 返回到以前的路线

history.goBack()

如何使用 react-router-domv6 实现这一目标?

【问题讨论】:

标签: reactjs react-router react-router-dom


【解决方案1】:

试试这个方法

import { useNavigate } from 'react-router-dom';

function YourApp() {
  const navigate = useNavigate();

  return (
    <>
      <button onClick={() => navigate(-1)}>go back</button>
    </>
  );
}

【讨论】:

  • 这真的很有帮助。谢谢
【解决方案2】:

在 V6 中,

import { useNavigate } from 'react-router-dom';
 
function App() {
  const navigate = useNavigate();
 
  return (
    <>
      <button onClick={() => navigate(-2)}>Go 2 pages back</button>
      <button onClick={() => navigate(-1)}>Go back</button>
      <button onClick={() => navigate(1)}>Go forward</button>
      <button onClick={() => navigate(2)}>Go 2 pages forward</button>
    </>
  );
}

【讨论】:

  • 我已经尝试过了,但在 v6 中 useHistory 不在 react-router-dom 中
  • 我的错。编辑我的 v6 答案。
【解决方案3】:

在旧版本的 react-router-dom 中存在 pop 函数

您可以通过以下方式联系他们:

const history = useHistory();
history.pop()

现在在 v6 中,您可以使用函数 useNavigate

const navigate = useNavigate();
navigate(-1) // you will go one page back
navigate(-2) // you will go two pages back

【讨论】:

    猜你喜欢
    • 2021-01-24
    • 2022-06-23
    • 2021-11-03
    • 2022-07-09
    • 1970-01-01
    • 2022-11-07
    • 2023-01-17
    • 2022-08-02
    • 2022-06-17
    相关资源
    最近更新 更多