简体   繁体   中英

Problem with setState ReactJS, done in todoList

Hello i have problem about change state after onClick with this function i dont know why this is doesnt work because console.log displayed difference value and i dont know why i cant set the same state.

`doneUndone = (index) => {
      console.log(!this.state.scores[index].done)
      const test = !this.state.scores[index].done
      this.setState({
           scores: test,
    })
}`

here will be all code of this aplication https://codepen.io/RetupK/pen/xxKmELd?editors=0010

As per your state scores is an array and in your method of done you are assigning Boolean value to it where as it must be an array itself. Because you're using .map() in your render method which only works with array not boolean.

What you need to do is change the done property of particular object in scores and pass the newly updated scores object to setState method and it will work.

  doneUndone = (index) => {
        this.state.scores[index].done = !this.state.scores[index].done
        this.setState({
            scores: this.state.scores,
        }) 
  }

If you use this.state to get previously done value you might have problems when you fire doneUndone method multiple times (eg clicking button few times in a row). That's why I suggest such solution:

doneUndone = index => {
  this.setState(state => ({
    scores: state.scores.map((score, idx) =>
      idx === index ? { ...score, done: !score.done } : score
    )
  }));
};

The doneUndone method isn't updating the state properly. You can check the method form here.

  doneUndone = (index) => {
    const score = this.state.scores[index];
    const updatedScore = {...score, done: !score.done};
    const updatedScores = [...this.state.scores];
    updatedScores[index] = updatedScore;
    this.setState({
        ...this.state,
        scores: updatedScores
    })

}
  doneUndone = (index) => {


        let modScores = this.state.scores;
         modScores[index].done=!this.state.scores[index].done

        this.setState({
            scores: modScores
        })

    }

cleaner way to do it

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