在 ReactJs 中添加查询参数时“返回”按钮不起作用

unp*_*ble 5 web reactjs react-router

让我介绍一下我正在做的事情导致了这个问题。我的 React Web 应用程序中有 3 条路线:

  1. "/"用于主页。
  2. "/page2"对于第2页。
  3. "/page3"对于第3页。

现在,当我进入路线时"/page2",我会在 URL 中推送一个查询参数,以呈现 page2 中的默认选项卡,使 URL 为"/page2?activeTab=tabId“。简而言之,当我尝试访问"/page2"它时,它总是会将 URL 设置为"/page2?activeTab=tabId".

现在的问题是当我第一次登陆 Page2 并尝试按浏览器上的后退按钮时。我一次又一次地重新渲染 page2。原因是:假设我第一次进入 page2,URL 将是"/page2?activeTab=tabId"。现在,当我按下后退按钮时,浏览器会删除查询参数并呈现 URL "/page2"。因此,每当 URL 再次呈现我的代码时,都会将其转换为"/page2?activeTab=tabId". 因此,我无法返回并只能停留在第二页。

我需要这方面的帮助。如何消除或者避免这个问题呢?

Dre*_*ese 4

您可以检查位置搜索参数,如果为空,则计算新的路径 URL 并替换历史记录中的当前位置。

  1. 检查位置搜索查询
  2. 如果搜索查询为空,则使用查询字符串构造新的路径 URL
  3. 重定向(替换)当前页面,以便后退按钮起作用

使用react-router-dom的useHistoryuseLocation反应钩子

const MyComponent = () => {
  const { replace } = useHistory();
  const { pathname, search } = useLocation();

  useEffect(() => {
    const tabId = <compute tab id>;
    const newPath = `${pathname}?activeTab=${tabId}`;
    if (!search) replace(newPath);
  }, [pathname, replace, search]);

  return (
    ...
  );
};
Run Code Online (Sandbox Code Playgroud)

如果无法使用react-router-dom的react hooks,那么您可以使用withRouter高阶组件来装饰您的组件,并从注入的道具中访问相同的值。

const MyComponent = ({ history, location }) => {
  const { replace } = history;
  const { pathname, search } = location;

  useEffect(() => {
    const tabId = <compute tab id>;
    const newPath = `${pathname}?activeTab=${tabId}`;
    if (!search) replace(newPath);
  }, [pathname, replace, search]);

  return (
    ...
  );
};

export withRouter(MyComponent);
Run Code Online (Sandbox Code Playgroud)

编辑 go-back-button-is-not-working-when-added-a-query-param-in-reactjs