ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-11-08 03:37:43  阅读:805  来源: 互联网

标签:reactjs local-storage javascript


我的初始状态为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
  }

标签:reactjs,local-storage,javascript
来源: https://codeday.me/bug/20191108/2005289.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有