React Router - 如何确定后退按钮是否被点击? [英] React Router - How to Determine If Back button was hit?
问题描述
我有这些场景
设置页面 -> 结果页面 -> 详情页面
Settings Page -> Results Page -> Details Page
用户选择设置,点击下一步,获得结果,然后点击进入更多细节.
User chooses settings, clicks next, gets results and then clicks into more details.
详情页 -> 结果页
用户从详细信息页面返回结果页面.这会导致完全重新渲染,导致我毫无意义地再次访问服务器(我将结果存储在数组中).
User goes back to Results page from Details Page. This causes a full re-render, causing me to hit the server again for no point(I have the results stored in an array).
详情页 -> 结果页 -> 设置页 -> 结果页
Details Page -> Results Page -> Settings Page -> Results Page
用户转到详细信息,然后返回结果(想要获取存储的结果),然后返回设置页面,进行更改,然后返回结果页面(现在我想再次从服务器获取完整数据).
The user goes to details, then back to results(want to grab stored results), then goes back to settings page, makes changes and then goes back to results page(now I want a full grab from server again).
我想知道 react 路由器中是否有可以确定我是通过浏览器历史记录进入页面还是向前移动的.
I am wondering if there is away in react router to determine if I came to the page via the browser history or if I was going in a forward motion.
推荐答案
在 React Router 中,如果路由器调用该组件的子路径,则该组件保持挂载状态.因此,在您的示例中,您可以执行以下操作:
In React Router, the component stays mounted if router calls for paths that are children of that component. So, in your example, you can do something like the following:
<Route path="items" component={Results}>
<Route path=":id" component={Detail} />
</Route>
这样,当Detail
组件被挂载时,Results
组件不会被卸载,因为Detail
是Results代码>.但是,如果您不希望在 Detail 中看到 Results 组件被渲染,则只能在其存在时渲染子组件.类似于以下内容:
This way, Results
component does not get unmounted when Detail
component is being mounted because Detail
is a child of Results
. However, if you do not want to see Results component getting rendered when you are in Detail, you can only render children when they exist. Something like the following:
class Results extends React.Component {
render() {
if (this.props.children) {
// This will enter Detail component
return this.props.children;
}
return (
// Render results component
);
}
}
这篇关于React Router - 如何确定后退按钮是否被点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!