【问题标题】:How i can save the toggle state and don't lose after refresh the page我如何保存切换状态并且在刷新页面后不会丢失
【发布时间】:2022-03-22 16:03:43
【问题描述】:

你好,我的项目主要是通过 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 之外,还有什么地方可以保存状态标签吗?

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

    在卸载时将状态保存在 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));
    }
    

    【讨论】:

    • 它有效,但是当我切换回来时,有时需要不止一次才能返回,为什么?这与persistedReducer有关吗?
    • PersistReducer 仅在 redux 存储中发生变化,可能是因为状态设置不正确
    猜你喜欢
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 2019-02-09
    • 2020-02-29
    • 1970-01-01
    • 2020-09-07
    • 2014-07-20
    • 1970-01-01
    相关资源
    最近更新 更多