简体   繁体   English

Javascript,ReactJs setState不起作用

[英]Javascript, ReactJs setState not working

I am learning react and I have this tutorial online quiz-react, so i try to make few adjustment, I want user to click on HellYa it will increment for example answers type - "Brown" "D" "JP" each by +1, this is my quizQuestion.js 我正在学习反应,并且已经在本教程中进行在线问答,所以我尝试进行一些调整,我希望用户单击HellYa,它将使答案类型增加-例如,“ Brown”,“ D”,“ JP”分别增加+1 ,这是我的quizQuestion.js

{
 question: "I am task oriented in order to achieve certain goals",
 answers: [
  {
    type: "Brown,D,JP",
    content: "Hell Ya!"
  },
  {
    type: " ",
    content: "Nah"
  }
 ]
},

My Constructor for init state is as follow 我的初始化状态构造函数如下

this.state = {
  counter: 0,
  questionId: 1,
  question: '',
  answerOptions: [],
  answer: '',
  answersCount: {
    Green: 0,
    Brown: 0,
    Blue: 0,
    Red: 0,
    A: 0,
    B: 0,
    C: 0,
    D: 0,
    EI: 0,
    SN: 0,
    TF: 0,
    JP: 0
  },
  result: ''
};

and following the tutorial, i am using react-addons-update for updating the answerCount and answer, here is my function 在本教程之后,我正在使用react-addons-update来更新answerCount和answer,这是我的功能

setUserAnswer(answer) {
 if (answer.trim()) {
   const answer_array = answer.split(',');
   let updatedAnswersCount = null;
   answer_array.forEach((answer) => {
     updatedAnswersCount = update(this.state.answersCount, {
      [answer]: {$apply: (currentValue) => currentValue + 1}
    });
  }, this);
  this.setState({
    answersCount: updatedAnswersCount,
    answer: answer
  });
 }
}

But after several attempts i still cannot figure out how to individually increment answer type by 1, right now it only update JP +1 for example but it does not update Brown and D, what should i do? 但是经过几次尝试,我仍然不知道如何将答案类型分别递增1,例如,现在它仅更新JP +1,但不更新Brown和D,我该怎么办? thanks 谢谢

It seems it is always using the current state as the base object, so only the last answer inside the foreach will be updated. 似乎总是使用当前状态作为基础对象,因此只会更新foreach中的最后一个答案。

Try the following: 请尝试以下操作:

setUserAnswer(answer) {
 if (answer.trim()) {
   const answer_array = answer.split(',');
   let answerCountUpdates = update(this.state.answersCount, {$merge: {}}) // copy this.state.answersCount, will search a better way

   answer_array.forEach((answer) => {
     answerCountUpdates = update(answerCountUpdates, {
      [answer]: {$apply: (currentValue) => currentValue + 1}
     });
   }, this);

   updatedAnswersCount = update(this.state.answersCount, {$merge: answerCountUpdates})

   this.setState({
     answersCount: updatedAnswersCount,
     answer: answer
   });
  }
}

It looks like you've named your forEach() 's iteration object "answer" as well as the parameter passed in to setUserAnswer() . 看来您已经将forEach()的迭代对象命名为“ answer”,以及传递给setUserAnswer()的参数。 Try changing one of these, as it's probably causing problems. 尝试更改其中之一,因为这可能会引起问题。

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

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