简体   繁体   中英

persist react data in react after page change

I am using react and everytime after navigating away from a page, the state goes back to original state. I have a state that is set when a user clicks on a button. This handles the setState of listView which is a boolean. So if listView is true, then the view would be listView and vice versa. The issue is that if I choose the other view, and refresh the page, immediately after it would go back to listView. Now I saw how to persist state using hooks by doing some research but I couldnt find an example of doing this in a class component that really is similar to my example. Please see my code. Thanks!

constructor(props) {
    super(props);
    this.state = {
      listView: true,
    };
  }

And the toggle area that setStates of the listView to be true or false, not really necessary, but just in case:

 <ToggleButtonGroup className={classes.toggleButtonContainer} exclusive orientation="horizontal">
       <ToggleButton className={listView ? classes.selectedToggleButton : '' } selected={listView} onClick={() => this.setState({ listView: true })} value="list" aria-label="list">
         <Icon fontSize="large" color="default">view_list</Icon>
                </ToggleButton>
                <ToggleButton className={!listView ? classes.selectedToggleButton : '' } selected={!listView} onClick={() => this.setState({ listView: false })} value="module" aria-label="module">
                  <Icon fontSize="large" color="default">view_module</Icon>
                </ToggleButton>
         </ToggleButtonGroup>

You can achieve this with different methods:

  1. React-Redux , alternative Context API

  2. Redux Persist Example

  3. Adding and Fetching state value from localStorage like this:

     constructor(props) { super(props); this.state = { listView: JSON.parse(localStorage.getItem('listView')) || [] } } renderListView = (selection) => {... this.setState({ listView: selection },() => { localStorage.setItem('listView', JSON.stringify(this.state.listView)) }); }
  4. Pushing into URL as query param after every response change:

     history.push({pathname: 'path/', search: '?' + Qs.stringify(params)}); //fetch the params from URL params = Qs.parse(nextProps.location.search.substring(1)); //add it to your local state of particular component this.setState({selectedOption: params.selectedOption});

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