简体   繁体   English

使用反应路由器而不丢失“ setState”状态?

[英]Using react router without loosing “setState” state?

I have a React app that takes the user through various steps. 我有一个React应用程序,可以引导用户完成各个步骤。 I want to have the ability to use the browser's "back" button to go back to a previous step. 我希望能够使用浏览器的“后退”按钮返回上一步。 Now I'm thinking of using react-router to do this. 现在我正在考虑使用react-router来做到这一点。

Currently, I am simply reacting to events and calling setState on my top-level component. 当前,我只是对事件做出反应,并在顶层组件上调用setState。

My question: Does all state have to be reflected in the URL, or saved into local storage? 我的问题:是否所有状态都必须反映在URL中或保存到本地存储中? Or can I keep the component's state and just have react-router change some props on the top-level component? 还是可以保留组件的state而只让react-router更改顶级组件上的一些props When I do that, do I risk loosing the component's state (eg because React doesn't identify the old and the new components)? 当我这样做时,是否冒着失去组件state风险(例如,因为React无法识别旧组件和新组件)?

I want to have simple URLs like /step1 , /step2 ... . 我想要简单的网址,例如/step1/step2 ...。 These do not reflect everything that is going on in the app. 这些不能反映应用程序中正在发生的一切。 Specifically, I don't need or want the ability to directly enter such an URL. 具体来说,我不需要或不希望能够直接输入这样的URL。 There are also privacy concerns. 还存在隐私问题。 I am happy with having the application's state in the main component's ephemeral state . 我对使应用程序的状态处于主要组件的短暂state感到满意。 In other words, my application's state is not a pure function of the route. 换句话说,我的应用程序的状态不是路由的纯粹功能。

I want to mainly use react-router to make the back button act as a glorified undo / go to last step button, and only secondly to navigate to other components. 我想主要使用react-router来使后退按钮充当美化的撤消/转到最后一步按钮,仅次于导航到其他组件。 Any idea or small snippet showing how to do that? 任何想法或小片段显示如何做到这一点? Or is react-router not suited for this? 还是不适合使用React-Router?

When React navigates from one component hierarchy to another (such as react-router links / history navigation) it only unmounts the components that do not exist in the new component hierarchy. 当React从一个组件层次结构导航到另一个组件层次结构(例如react-router链接/历史记录导航)时,它只会卸载新组件层次结构中不存在的组件。 State is only lost in unmounted components. 状态仅在未安装的组件中丢失。 If your state is properly stored at the top level which only goes through rerendering and not remounting, you should retain it. 如果您的状态正确存储在仅通过重新渲染而不进行重新装载的顶层,则应该保留它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM