如何保存切换状态,刷新页面后不会丢失

时间:2018-05-30 09:19:08

标签: javascript reactjs redux react-redux

你好,我的项目主要来自react和redux, 我在这个应用程序中建立应用程序,当它将数据同步到日历时切换,我希望它在刷新页面后保持切换。 这是一些代码

constructor(props){
    super(props);

    this.state ={
        value: 1,
        toggled: undefined
    };
    this.handleToggle = this.handleToggle.bind(this);
} 

handleToggle = (event,toggled,index) => {
    this.setState({toggled});

    if (toggled == true){
         ///sync the Calendar code////
    }else{
        /// un sync ////
    }
}

并在此之后返回

  <Toggle label={translate('sync')}
          onToggle={this.handleToggle}
          toggled={this.state.toggled}
  />

是否可以保存除this.state以外的状态标记?

1 个答案:

答案 0 :(得分:0)

在卸载时保存localStorage中的状态并在初始安装时重新填充

constructor(props){
    super(props);
    const local = localStorage.getItem('state');
    if(local) {
       this.state =JSON.parse(local)
    } else {
          this.state ={
               value: 1,
               toggled: undefined
          };
          this.handleToggle = this.handleToggle.bind(this);
    }
}

handleToggle = (event,toggled,index) => {
    this.setState({toggled});
    if (toggled == true){
         ///sync the Calendar code////
    }else{
       /// un sync ////
}

componentWillUnmount() {
   localStorage.setItem('state', JSON.stringify(this.state));
}
相关问题