首页 > 解决方案 > 再次转到当前活动的路线时,如何强制到达路由器(在 Gatsby 中)重新加载页面?

问题描述

我有类似以下的情况:

<Link to="products" state={{ category: "all" }}>All Products</Link>
<Link to="products" state={{ category: "lawnmowers" }}>Lawnmowers</Link>
<Link to="products" state={{ category: "saddles" }}>Saddles</Link>

这个想法是,根据用户单击的链接,我会过滤掉产品以仅显示该类别。我对该解决方案的易用性感到相当满意,理想情况下不想更改它。

当我在不同的路线上时,这很好用,例如我在/about里面并单击割草机链接,我会得到一个充满割草机的页面。但是,如果我在/products路线上,单击任何其他也指向/products自身的链接根本不会执行任何操作。该站点没有刷新,状态没有改变,而且 Gatsby 或 Reach 似乎以某种方式阻止了这一点。

有什么方法可以规避或禁用此行为并以某种方式强制 Gatsby 重新加载/重新呈现页面?

标签: reactjsgatsbyreach-router

解决方案


React rerenders the page when props or state change.

if I'm on the /products route, clicking any other link that also leads to /products itself simply does nothing

This implies that neither props nor state change because you're on the same route?! Then you will not get a rerender. If I'm mistaken please rephrase and be more specific with your question.

One possible solution: By clicking the link you also trigger a function that changes the state. This means, you would have to move away from the concise <Link ... /> and instead implement a whole lot of state management code. But there is no way around if you filter by changing state.

Use React hooks useState for changing state and useEffect for applying the state change. Use Reach Router's navigate to trigger the state change.


推荐阅读