反应本地存储

时间:2018-11-14 11:57:21

标签: javascript reactjs

我正在尝试通过React中的click函数来增加全局计数器,并将增加的计数器保留在localStorage中。当前,它仅在您位于同一页面上以及将数据传递到另一页面时才起作用。但是,一旦您单击返回并再次增加计数器,数据将从零开始重置,而不是从存储的计数器开始。如果这有意义。救命!如何从存储的数据而不是状态数据中计数?

代码如下:

 handleIncrement = counter => {
    const courses = [...this.state.courses]; //clones new arrays of counters
    const index = courses.indexOf(counter); // gets obj index that we receive as parameter
    courses[index] = {...counter}; //sets current index to new cloned counter
    courses[index].value++; //increments current index
    //console.log(this.state.counters[index]);
    let value = this.state.courses[0].value + this.state.courses[1].value + this.state.courses[2].value + this.state.courses[3].value +  this.state.courses[4].value + this.state.courses[5].value
    let name1 = this.state.courses[0].name
    localStorage.setItem("list", value );
    this.setState({courses}); //updates the view
};

2 个答案:

答案 0 :(得分:0)

每次启动handleIncrement时,您都将localStorage设置为值“ value”。 “价值”来自您所在的州:

    let value = this.state.courses[0].value + this.state.courses[1].value + this.state.courses[2].value + this.state.courses[3].value +  this.state.courses[4].value + this.state.courses[5].value

每次重新加载时,似乎您的状态又从零开始。每次启动handleIncrement时,都会为localStorage赋予新的值:

    localStorage.setItem("list", value );

请记住,您应该在某个时候从localStorage检索值,

    const savedValue = localStorage.getItem("list");

答案 1 :(得分:0)

我只是重新设置了click事件的逻辑,并且它起作用了。这是我的解决方案:

handleIncrement =计数器=> {   如果(localStorage.getItem(“ list”)=== null){

  localStorage.getItem("list" );

}else{
  const courses = [...this.state.courses]; //clones new arrays of counters
  const index = courses.indexOf(counter); // gets obj index that we receive as parameter
  courses[index] = {...counter}; //sets current index to new cloned counter

  courses[index].value++; //increments current index
  //console.log(this.state.counters[index]);
  let allcookies = Number(localStorage.getItem('list')) + 1
  localStorage.setItem("list", allcookies );


  this.setState({courses}); //updates the view
   //let name1 = this.state.courses[0].name;

}

};