简体   繁体   中英

How would a share the state of the same React component across multiple pages?

I have a React Component with a toggle on it (on or off). The on / off state is handled by the components own state (this.state).

But I want that state to remain when the user goes from one page to the next. For instance they are on home.html and then when user clicks to another page like about.html.

Also this is not a single page app. Do I want Redux or Mobox or some other state management tool? Suggestions are welcomed.

But I want that state to remain when the user goes from one page to the next.

As has been said in comments probably the most straight-forward way is to just store the state to localstorage and retrieve it when the component mounts.

class Toggle extends Component {
  componentDidMount() {
    const storedValue = localStorage.getItem("my_value");
    if (storedValue) {
      this.setState({ value: storedValue });
    }
  }
  handleChange = e => {
    const value = e.target.value;
    this.setState({ value });
    localStorage.setItem("my_value", value);
  }
  render() {
    return ...
  }
}

Also this is not a single page app. Do I want Redux or Mobox or some other state management tool? Suggestions are welcomed.

No, Redux and Mobx aren't necessary, they are state containers that have ways to persist to localstorage (for example redux-localstorage and mobx-localstorage ), but the key is just persisting to localstorage.

If you are not moving pages (whole page refresh) and only using different components then you can simply define a state in parent component and pass it in the child components along with a function that would toggle the state.

Function would look like this:

ToggleState = newState => this.setState({ myState : newState });

Pass this function as prop to child component.

Use it in child component as

This.props.toggle(newState);

**but if it is across multiple pages the you can go for localstorage **

Hope this resolves your issue.

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