【问题标题】:Get and use the previous state from local storage从本地存储中获取并使用之前的状态
【发布时间】:2019-06-08 05:22:01
【问题描述】:

我正在使用 ant design react 构建 3 个不同的模式/单选按钮,我想从本地存储中获取以前的状态并将其分配给我的值。

只有当我对值进行硬编码时它才有效,必须有一种更简洁的方法来实现这一点。

  class Settings extends React.Component {
    state = {
      mode: 'Something Mode 1',
    }


  componentDidMount() {
      chrome.storage.local.get('AllModes', (result) => {
        this.setState({ mode: result.AllModes})
      })
    }



      handleMode () {
          let currentMode = localStorage.getItem(['AllModes']);
        console.log(currentMode)
        this.setState(( currentMode ) => {
          return {
              mode: currentMode.mode
          }
      })
    }

  <RadioGroup onChange={this.onChange}
              className="radio__group"
              defaultValue={this.handleMode}>
  </RadioGroup>
  }

【问题讨论】:

    标签: javascript reactjs local-storage


    【解决方案1】:

    有几种方法可以做到这一点,但我将描述一种简单的方法。 您可以将localStorage 中的组件状态保存为 JSON 编码的字符串,并在重新创建组件时恢复它。

    我们可以定义我们的保存和加载方法:

    function getStoredComponentState(initialState) {
        const storedState = localStorage.getItem(checkedStorageKey);
        return storedState ? JSON.parse(storedState) : initialState;
    }
    
    function storeComponentState(state) {
        localStorage.setItem(checkedStorageKey, JSON.stringify(state))
    }
    

    我们从存储的状态初始化我们的状态,提供一个默认值以防没有存储的先前状态:

    constructor() {
        super();
        this.state = getStoredComponentState({
          checked: false,
        })
      }
    

    我们会在发生更改时保留对存储所做的任何更改:

    setState(state) {
        super.setState(state);
        storeComponentState(state);    
      }
    

    而且它有效!您可以进行更改,刷新页面,然后查看之前的状态是否已恢复。 JSFiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-28
      • 2021-01-12
      • 2022-01-18
      • 2019-06-11
      • 1970-01-01
      • 1970-01-01
      • 2013-12-15
      • 1970-01-01
      相关资源
      最近更新 更多