[英]React JS how to remember the clicked item in a list when I pass to next page
I listed some countries in my Country.js page using ListItem.我使用 ListItem 在我的 Country.js 页面中列出了一些国家/地区。 I created a CodeSandbox and this is the link for it:
我创建了一个 CodeSandbox,这是它的链接:
I want the program to remember the clicked list item in the list in Country.js file and when I go to next page (press the next button) and back again (press the back button), the selected item before going to next page should also be selected.我希望程序记住 Country.js 文件中列表中单击的列表项,当我转到下一页(按下一页按钮)并再次返回(按后退按钮)时,转到下一页之前的所选项目应该也被选中。 Sorry for the bad stylings, I did not add them.
抱歉样式不好,我没有添加它们。
Note: I implemented this feature in forms (radio group) but, I could not do this in a list.注意:我在表单(无线电组)中实现了此功能,但是,我无法在列表中执行此操作。
The problem is that your state is currently at the level of your CountryList component so every time this component is unmounted, its state disappear.问题是您的状态当前处于 CountryList 组件的级别,因此每次卸载此组件时,其状态都会消失。
What you need to do is lift up the state of the component in your UserForm component so it won't disappear when you change page您需要做的是在您的 UserForm 组件中提升组件的状态,以便在您更改页面时它不会消失
there is a lot solution for this case (holds data in):这种情况有很多解决方案(保存数据):
Of course, the state can be transferred between the components (but only one way - there is no two way data binding as in angular)当然,状态可以在组件之间传输(但只有一种方式 - 没有像 angular 那样的两种方式数据绑定)
As context and redux are more global concepts - I suggest you save the data at each step to sessionStorage and finally collect that data and send it to API or whatever.由于 context 和 redux 是更全局的概念 - 我建议您将每个步骤的数据保存到 sessionStorage 并最终收集该数据并将其发送到 API 或其他任何地方。
// Save data to sessionStorage
sessionStorage.setItem('Country', countryName);
sessionStorage.setItem('FilmSurvey', surveyName);
// Get saved data from sessionStorage
var dataCountry = sessionStorage.getItem('Country');
var dataSurvey = sessionStorage.getItem('FilmSurvey');
Then, when it works,that you refactor it somehow.然后,当它工作时,你以某种方式重构它。
And general advice - I recommend using Hooks - they are more consistent and newer和一般建议 - 我建议使用Hooks - 它们更加一致和更新
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.