简体   繁体   中英

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

{
 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

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? 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.

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() . Try changing one of these, as it's probably causing problems.

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