简体   繁体   中英

React setState() doesn't return updated state on callback

I am trying to create a quiz app and in the componentDidMount() function I am trying to update and return some questions. However, when I'm console logging the state after setState(). The same objects are returned.

export default class Multiple extends Component {
  constructor(props) {
    super(props);
    this.state = {
      questions: [
        {
          id: 1,
          question: "How many in a couple",
          answers: [{ option1: "1", option2: "2", option3: "3", option4: "4" }],
          answer: "2"
        }
      ],
      currentQ: ""
    };
  }

  componentDidMount() {
    const currentQs = this.state.questions;
    console.log(currentQs);
    this.setState(prevState => {
      console.log(prevState);
      return (
        {
          questions: currentQs,
          currentQ: this.getRandomQ(currentQs)
        },
        console.log(this.state)
      );
    });
  }

  getRandomQ(currentQs) {
    const question = currentQs[Math.floor(Math.random() * currentQs.length)];
    return question;
  }

  render() {
    return (
      <div className="container">
        <Quiz
          question={this.state.currentQ.question}
          answers={this.state.currentQ.answers}
          answer={this.currentQ.answer}
        />
      </div>
    );
  }
}

Sorry, I'm new to react and I'm struggling to gauge my way around, especially in creating a quiz application.

You are currently returning undefined from the function given to setState because of how the , operator works.

 const state = ( { questions: ['foo', 'bar'], currentQ: 'bar' }, console.log('baz') ); console.log(state); 

You want to give a function as second argument to setState if you want it be called after the state has been set.

this.setState(
  prevState => {
    console.log(prevState);
    return {
      questions: currentQs,
      currentQ: this.getRandomQ(currentQs)
    };
  },
  () => console.log(this.state)
);

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