首页 > 解决方案 > ReactJS:如何使用 localStorage 更新属性状态?

问题描述

我有一个具有以下初始状态的组件:

  constructor(props) {
    super(props)
    this.state = {
      currentId: 0,
      pause: true,
      count: 0,
      storiesDone: 0
    }
    this.defaultInterval = 4000
    this.width = props.width || 360
    this.height = props.height || 640
  }

我必须从开始currentId = 0然后更新组件的状态,即使在页面刷新之后也是如此。

我想currentId = 1在保持1.

当我尝试currentId = localStorage.getItem('currentId')在上面的代码中替换时,出现属性无法更改的错误。

    var currentId = this.state.currentId;    
      localStorage.setItem( 'currentId', 1);
      console.log(currentId);
      localStorage.getItem('currentId');

我也试过:

  _this.setState((state) => {
      return {currentId: localStorage.getItem('currentId')};
    });

标签: javascriptreactjslocal-storage

解决方案


持久化的值类型localStorage 必须是字符串

考虑修改与之交互的代码,localStorage以便在将状态值currentId传递给之前先将其转换为字符串localStorage.setItem()

另请注意,字符串值是在存在键时返回localStorage.getItem(),这意味着您应该解析返回的值以获取currentId为数字。

类似这样的东西应该可以工作:

const saveCurrentId = () => {    

    const { currentId } = this.state;    

    /* Format string from value of currentId and persist */
    localStorage.setItem( 'currentId', `${ currentId }`);
}

const loadCurrentId = (fallbackValue) => {

    /* Load currentId value from localStorage and parse to integer */
    const currentId = Number.parseInt(localStorage.getItem('currentId'));

    /* Return currentId if valid, otherwise return fallback value */
    return Number.isNaN(currentId) ? fallbackValue : currentId;
}

使用上面的代码,您可以更新组件构造函数以自动加载和应用持久化currentId,如下所示:

 constructor(props) {
    super(props)
    this.state = {

      /* Use 0 as fallback if no persisted value present */
      currentId: this.loadCurrentId( 0 ), 

      pause: true,
      count: 0,
      storiesDone: 0
    }
    this.defaultInterval = 4000
    this.width = props.width || 360
    this.height = props.height || 640
  }

推荐阅读