简体   繁体   中英

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. I created a CodeSandbox and this is the link for it:

My Code

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. 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.

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

there is a lot solution for this case (holds data in):

  • a) context ,
  • b) redux - redux persist - holds in persistence
  • c) sessionStorage

Of course, the state can be transferred between the components (but only one way - there is no two way data binding as in 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.

// 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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