React-router-dom 如何在不使用usingHistory的情况下使用goBack功能

React-router-dom how to use the goBack function without usingHistory

如何通过代码模拟按下浏览器中的“后退”按钮?

const history = useHistory()
history.goBack()

我知道我也可以做到这一点,但是据我了解在新版本的react-router-dom useHistory 被更改为useNavigate,它没有goBack() 功能。如何在不回滚 react-router-dom?

的情况下返回最后一页

...in the new versions of react-router-dom useHistory was changed to useNavigate, which has no goBack() function.

这并不完全准确。在 react-router-dom@6 中,useHistory 挂钩被 替换为 useNavigate 挂钩。 useNavigate 挂钩 returns navigate 函数 而不是 具有导航方法的 history 对象。

useNavigate

declare function useNavigate(): NavigateFunction;

interface NavigateFunction {
  (
    to: To,
    options?: { replace?: boolean; state?: any }
  ): void;
  (delta: number): void;
}

进一步

The navigate function has two signatures:

  • Either pass a To value (same type as ) with an optional second { replace, state } arg or
  • Pass the delta you want to go in the history stack. For example, navigate(-1) is equivalent to hitting the back button.

您想使用 delta 参数。如果您从 RRDv4/5 回忆起 history.goBack() 等同于 history.go(-1).

v4 history

// Go back to the previous history entry. The following
// two lines are synonymous.
history.go(-1);
history.goBack();

解决方案

How can I go back to the last page without rolling back react-router-dom?

react-router-dom@6发出后退导航,即POP:

const navigate = useNavigate();

navigate(-1);