[英]React setState() doesn't return updated state on callback
我正在嘗試創建一個測驗應用程序,並在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>
);
}
}
抱歉,我是新來的人,我正在努力評估自己的出路,尤其是在創建測驗應用程序時。
由於運算符的工作方式,
您當前正在從給setState
的函數中返回undefined
。
const state = ( { questions: ['foo', 'bar'], currentQ: 'bar' }, console.log('baz') ); console.log(state);
如果要在設置狀態后調用該函數,則想將其作為setState
第二個參數。
this.setState(
prevState => {
console.log(prevState);
return {
questions: currentQs,
currentQ: this.getRandomQ(currentQs)
};
},
() => console.log(this.state)
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.