简体   繁体   中英

React LocalStorage

I'm trying through a click function in React to increase a global counter and keep the increased counter in localStorage. Currently its only working when you're on the same page and when you pass the data to another page. But as soon as you click back and increment the counter again, the data is reset starting from zero instead of the stored counter. if this makes sense. Help! how can i count from the stored data instead of from the state data?

Here's the code:

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

Every time you are launching handleIncrement, you are setting your localStorage to the value "value". "value" is coming from your state:

    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

Every time you are reloading, it seems your state is starting from zero again. And every time you are launching handleIncrement, you are giving your localStorage a new value:

    localStorage.setItem("list", value );

Remember your should at some point retrieve the value from your localStorage as such:

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

I just redid the logic of the click event and it worked. Here's my solution:

handleIncrement = counter => { if (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;

}

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM