javascript-ReactJS:如何使用localStorage更新属性状态?

我的初始状态为component

  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开始,然后即使在刷新页面后也要更新组件的状态.

我要在保持值1之后恢复currentId = 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')};
    });

解决方法:

值类型坚持到localStorage must be a string.

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

还要注意,当存在键时,由localStorage.getItem()表示string values are returned,这意味着您应该解析返回的值以获得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
  }
上一篇:javascript-SemanticUI搜索-下拉选择不填充输入


下一篇:javascript-使用SSR响应HMR