如何使用 React Router 维护路由之间的状态? [英] How to maintain state between routes with React Router?
问题描述
我的应用程序有一个包含 4 个选项卡的选项卡组件.每个选项卡的内容都设置为单独的组件.我正在用 4 条不同的路线替换选项卡.我去掉了选项卡并使用 react-router
设置了 4 个路由,每个路由一个用于 4 个组件.
My application had a tab component with 4 tabs. The content of each tab was set up as a separate component. I'm replacing the tab with 4 different routes. I got rid of the tab and used react-router
to set up 4 routes, one for each of the 4 components.
在导航到选项卡和从选项卡导航时,选项卡的内容将保持其状态.例如,假设用户已滚动到一个选项卡中的列表底部.如果用户导航到不同的选项卡并返回,列表将保持滚动到底部.
The content of a tab would maintain its state when navigating to and from the tab. For example, say the user has scrolled to the bottom of a list in one tab. If the user navigates to a different tab and comes back, the list would remain scrolled to the bottom.
我无法通过路由实现这种行为.我注意到当我从一条路线导航到另一条路线时,组件会重新实例化(不仅仅是重新渲染).
I'm not able to achieve this behavior with routes. I noticed that when I navigate from one route to another, the components are re-instantiated (not just re-rendered).
我想实现类似选项卡的行为.我知道有一个名为 UI-Router-Extras 的 Angular 库可以提供深度状态重定向.但是我找不到 React 的类似选项.我已经尝试过 react-router
和 react-router-component
并且当它的路由变为活动时都重新实例化一个组件.
I want to achieve the tab-like behavior. I know that there's a library called UI-Router-Extras for Angular that provides deep state redirect. But I can't find a similar option for React. I have tried react-router
and react-router-component
and both re-instantiate a component when its route becomes active.
是否有解决方案可以为 React 中的路由实现这种行为?
Is there a solution to achieve this behavior for routes in React?
推荐答案
您有两个选择,使用 Redux,或基于选项卡显示/隐藏组件.
You have two options, use Redux, or show/hide components based on tabs.
这是显示/隐藏组件的示例
Heres an example to show/hide components
{this.state.showAboutMe ? <AboutMeComponent navigation={this.props.navigation} props={this.props.user} /> : undefined}
这篇关于如何使用 React Router 维护路由之间的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!