0

I using react to build my page

I have array['kiwi','papaya','apple']

And I using these code

  if(this.state.recordFood.indexOf('kiwi') !=-1){
  this.setState({
    feedbackDisplay: [...this.state.feedbackDisplay,this.state.feedback[0].content]
  })
};
if(this.state.recordFood.indexOf('papaya') !=-1){
  this.setState({
    feedbackDisplay: [...this.state.feedbackDisplay,this.state.feedback[1].content]
  })
};
if(this.state.recordFood.indexOf('apple') !=-1){
  this.setState({
    feedbackDisplay: [...this.state.feedbackDisplay,this.state.feedback[2].content]
  })
};

if there is kiwi papaya apple in my array , it will concat different value to state feedbackdisplay, so after the code , I will have

this.state.feedback[0].content

this.state.feedback[1].content

this.state.feedback[2].content

in my state feedbackdisplay

but it all concat this.state.feedback[0].content to state feedback display

so I got

this.state.feedback[0].content

this.state.feedback[0].content

this.state.feedback[0].content

in my state feedbackdisplay

0

1 Answer 1

1

setState does not update the state immediately, so you should pass an updater function to setState if you are calling it multiple times in a row. This will ensure you are using most recent state.

this.setState((prevState, props) => ({ feedbackDisplay: [...prevState.feedbackDisplay, this.state.feedback[1].content] }));

Although making an array first and the calling setState once would be cleaner and easier to understand.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.