React setState()在回调上不返回更新状态

时间:2019-02-24 22:55:48

标签: javascript reactjs

我试图创建一个测验应用程序,并且在componentDidMount()函数中,我试图更新并返回一些问题。但是,当我在控制台上记录setState()之后的状态时。返回相同的对象。

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>
    );
  }
}

对不起,我是新来的人,我正在努力评估自己的出路,尤其是在创建测验应用程序中。

1 个答案:

答案 0 :(得分:4)

由于'y'运算符的工作原理,您当前正在从赋予undefined的函数中返回setState

,

如果希望在设置状态后调用const state = ( { questions: ['foo', 'bar'], currentQ: 'bar' }, console.log('baz') ); console.log(state);,则要将其作为第二个参数。

setState