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

我想在持续的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的值类型必须是字符串。

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

还要注意,当存在键时,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
  }

使用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
    }));
  }
}

最新更新