Javascript 状态未在React中更新
我在YouTube上观看关于react版本16中的一个测验应用程序的教程。状态和函数中有几个变量,这些变量在Javascript 状态未在React中更新,javascript,reactjs,setstate,Javascript,Reactjs,Setstate,我在YouTube上观看关于react版本16中的一个测验应用程序的教程。状态和函数中有几个变量,这些变量在setState的帮助下更新。未更新变量的值。更新这些变量的函数中包含以下内容。正在从componentDidMount函数调用此函数 displayQusetions = (questions = this.state.questions, currentQuestion, nextQuestion, previousQustion) => { let { currentQu
setState
的帮助下更新。未更新变量的值。更新这些变量的函数中包含以下内容。正在从componentDidMount
函数调用此函数
displayQusetions = (questions = this.state.questions, currentQuestion, nextQuestion, previousQustion) => {
let { currentQuestionIndex } = this.state;
if (!isEmpty(this.state.questions)) {
questions = this.state.questions;
currentQuestion = questions[currentQuestionIndex];
nextQuestion = questions[currentQuestionIndex + 1];
previousQustion = questions[currentQuestionIndex - 1];
const answer = currentQuestion.answer;
this.setState({
currentQuestion,
nextQuestion,
previousQustion,
answer
})
console.log(this.state.currentQuestion);
console.log(this.state.nextQuestion);
console.log(this.state.previousQustion);
console.log(this.state.answer);
}
}
我是新来的。请提供帮助。您可以在回调中检查状态更新值
this.setState({
currentQuestion,
nextQuestion,
previousQustion,
answer
},()=>{
console.log(this.state.currentQuestion);
console.log(this.state.nextQuestion);
console.log(this.state.previousQustion);
console.log(this.state.answer);
})
这个问题几乎每天都会被问到,请搜索。React状态更新是异步的,因此在之后立即记录只会从当前渲染周期中产生状态,请使用
setState
callback参数记录新状态。这回答了你的问题吗?使用setState
的第二个参数作为回调,该参数将在状态更新后执行。这是否回答了您的问题?