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

3

我有一个组件,其初始状态如下:

  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')};
    });

只需在构造函数中设置默认状态定义以使用本地存储值即可。 - John Ruddell
2个回答

2

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,如下所示:

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


将 "Original Answer" 翻译成 "最初的回答"。
 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
  }

我正在尝试使用这种方法,但它无法从控制台读取,我只看到“null”,当尝试localStorage.getItem('currentId')时。非常感谢您的更新。我会尝试最新的编辑。 - Jonas Kgomo
1
@JonasKgomo 不客气,如果你有任何问题,请告诉我。 - Dacre Denny
控制台显示“saveCurrentId已声明但从未使用”,而“localStorage”仍然返回null。然而,第二个变量“loadcurrentId”在构造函数中应用良好。 - Jonas Kgomo
@JonasKgomo很高兴听到loadCurrentId()起作用了 - 你是如何调用/使用saveCurrentId()的?像这样在onClick属性中应该可以工作:onClick = { () => this.saveCurrentId() } - Dacre Denny
@JonasKgomo 没问题 - 还有一件可能有用的事情是,您可以通过setState回调在状态更改后更新使用localStorage持久化的数据,像这样:this.setState({ currentId : newValue }, () => { this.saveCurrentId() }) - Dacre Denny
显示剩余2条评论

1
使用componentDidMount。看下面的代码。我添加了检查localStorage.currentId是否有值。如果有,检查localStorage.currentId的值是否与状态的currentId匹配,如果不匹配,则将状态更新为localStorage中的值。
state = {
  currentId: 0,
  pause: true,
  count: 0,
  storiesDone: 0
}
componentDidMount() {
  //Assign localStorage.get("currentId") to a variable
  const localCurrentId = localStorage.get("currentId");
  //Check if localCurrentId is not null or undefined
  if (localCurrentId) {
    this.setState(prevState => ({
      //Update state's currentId if the current value didn't match with localCurrentId
      currentId: prevState.currentId !== localCurrentId ? localCurrentId : prevState.currentId
    }));
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接