简体   繁体   English

setState ReactJS 的问题,在 todoList 中完成

[英]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.您好,我在使用此功能后 onClick 更改状态时遇到问题,我不知道为什么这不起作用,因为 console.log 显示差异值,我不知道为什么我不能设置相同的状态。

`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这里将是这个应用程序的所有代码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.因为你在渲染方法中使用 .map() ,它只适用于数组而不是布尔值。

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.您需要做的是更改分数中特定对象的完成属性,并将新更新的分数对象传递给 setState 方法,它会起作用。

  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).如果您使用this.state来获取先前完成的值,则在多次触发doneUndone方法时可能会遇到问题(例如,连续单击按钮几次)。 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. doneUndone方法未正确更新状态。 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更清洁的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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