简体   繁体   English

如何在多个页面上共享同一React组件的状态?

[英]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). 我有一个React组件,上面有一个开关(打开或关闭)。 The on / off state is handled by the components own state (this.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. 例如,它们在home.html上,然后在用户单击到诸如about.html之类的另一个页面时出现。

Also this is not a single page app. 而且这不是一个单页面的应用程序。 Do I want Redux or Mobox or some other state management tool? 我是否需要Redux或Mobox或其他状态管理工具? 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? 我是否需要Redux或Mobox或其他状态管理工具? 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. 不,Redux和Mobx不是必需的,它们是状态容器,可以持久存储到本地存储(例如redux-localstoragemobx-localstorage ),但是关键只是持久存储到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 }); ToggleState = newState => this.setState({myState:newState});

Pass this function as prop to child component. 将此功能作为道具传递给子组件。

Use it in child component as 在子组件中将其用作

This.props.toggle(newState); this.props.toggle(newState);

**but if it is across multiple pages the you can go for localstorage ** **但是如果跨多个页面,则可以进行本地存储**

Hope this resolves your issue. 希望这能解决您的问题。

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

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