React 中的状态没有更新
The state is not updating in React
我正在关注 YouTube 上关于 React 版本 16 中测验应用程序的教程。在状态和函数中有一些变量,这些变量在 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);
})
我正在关注 YouTube 上关于 React 版本 16 中测验应用程序的教程。在状态和函数中有一些变量,这些变量在 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);
})