如何访问React路由器中的历史堆栈?

Goo*_*mja 15 reactjs react-router

我正在尝试访问反应路由器的历史堆栈。

这是我想做的:

我使用react.js 和react-router 创建一个板。

如果用户单击板上的列表之一,则会转到详细信息页面。

假设用户点击列表中 id 为 3 的文章,react-router 会转到 id 3 文章的详细信息页面,url 形式如下。

localhost:3000/board/3
Run Code Online (Sandbox Code Playgroud)

在详细信息页面中,有一个转到列表按钮,当用户单击它时,页面将再次移动到列表页面,我将在这里使用history.back()

到目前为止,使用react-router 就很容易做到了。

但是,用户可以访问另一个页面的详细信息页面,例如个人资料页面。

如果用户通过个人资料页面访问详细信息页面,则转到列表按钮的行为应该有所不同。它将用户推送到用户列表页面。

总而言之,转到列表按钮的工作原理如下:

board -> detail -> click go to the list -> board
profile -> detail -> click go to the list -> user-list
Run Code Online (Sandbox Code Playgroud)

为了根据用户所在的位置将用户推送到不同的页面,我需要查看用户来自哪里,因此我需要查看历史堆栈,或者是否有其他方法可以检查用户来自哪个网址?

Dre*_*ese 17

您将react-router-dom无法直接访问浏览器的历史对象(即历史堆栈),但您不一定需要这样做,因为您可以使用路由状态发送“元”数据以及有关用户导航位置的路由转换从。

react-router-dom@6

关联

对于示例路线:<Route path="/detail">....</Route>您可以有多个指向该页面的链接,每个链接都提供唯一的状态。

示例链接:

<Link
  to="/details"
  state={{ from: 'board' }}
>
  to details from board
</Link>
Run Code Online (Sandbox Code Playgroud)

或者

<Link
  to="/details"
  state={{ from: 'profile'}}
>
  to details from profile
</Link>
Run Code Online (Sandbox Code Playgroud)

或用于命令式导航

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

const navigate = useNavigate();

navigate("/details", { state: { from: 'profile' } });
Run Code Online (Sandbox Code Playgroud)

路线状态放置在位置对象上,访问组件中的路线状态Details并相应地发出后续导航。

const targets = {
  board: "/board",
  profile: "/userlist",
};

...

const { state: { from } } = useLocation();
const target = targets[from] ?? "/board";

...

<Link to={target}>
  click go to the list
</Link>
Run Code Online (Sandbox Code Playgroud)

或用于命令式导航

const navigate = useNavigate();

navigate(target);
Run Code Online (Sandbox Code Playgroud)

react-router-dom@5

链接到:对象

对于示例路线:<Route path="/detail">....</Route>您可以有多个指向该页面的链接,每个链接都提供唯一的状态。

示例链接:

<Link
  to={{
    pathname: '/details',
    state: {
      from: 'board',
    }
  }}
>
  to details from board
</Link>
Run Code Online (Sandbox Code Playgroud)

或者

<Link
  to={{
    pathname: '/details',
    state: {
      from: 'profile',
    }
  }}
>
  to details from profile
</Link>
Run Code Online (Sandbox Code Playgroud)

或用于命令式导航

history.push({
  pathname: '/details',
  state: {
    from: 'profile',
  }
});
Run Code Online (Sandbox Code Playgroud)

路线状态放置在位置对象上,访问组件中的路线状态Details并相应地发出后续导航。

const targets = {
  board: "/board",
  profile: "/userlist",
};

...

const { state: { from } } = useLocation();
const target = targets[from] ?? "/board";

...

<Link to={target}>
  click go to the list
</Link>
Run Code Online (Sandbox Code Playgroud)

或用于命令式导航

history.push(target);
Run Code Online (Sandbox Code Playgroud)