我有一个问题:this.setState({score:counter});由于某种原因,它没有更新。为什么?即使我执行this.setState({score:5})或得分:“一个字符串”,它仍然不起作用。我想念什么吗?无论我做什么,状态都不会改变。我必须添加额外的描述,因为该网站不允许我发布我的问题。
displayResultsHandler = () => {
var counter = 0;
for(let i = 0; i < this.state.correctAnswers.length; i++) {
if(this.state.correctAnswers[i] === this.state.userAnswers[i]) {
counter = counter+1;
}
}
this.setState({
score: counter
});
console.log("counter: " + counter);
console.log("score: " + this.state.score); // For some reason, this is always zero
}
我在下面添加了完整的代码。也许会有帮助。
import React, { Component } from 'react';
import './App.css';
import Title from './Title/Title';
import Question from './Question/Question';
import Aux from './hoc/Aux';
import SubmitButton from './SubmitButton/SubmitButton';
class App extends Component {
state = {
questionArray: [
"What is 9+10",
"How many goals did Ronaldo score against Spain in the World Cup 2018",
"Who Stole Ronaldo's (CR7) greates ever goal?",
"Which one of these players ruined the NBA",
"Who is currently number 1 in the internet L rankings?"
],
answerChoicesArray: [
["1", "19", "21", "90", "-1"],
["1", "3", "5", "0", "-1"],
["Pepe", "Messi", "Casillas", "Benzema", "Nani"],
["Allen Iverson", "Kevin Durant", "Steph Curry", "Lebron James", "Russel Westbrook"],
["Drake", "Pusha T", "Russel Westbrook", "Lil Xan", "Russ"]
],
correctAnswers: ["21", "3", "Nani", "Kevin Durant", "Russ"],
userAnswers: ["", "", "", "", ""],
score: 0
}
updateUserAnswersHandler = (oldArray, index, value) => {
const newArray = oldArray;
newArray[index] = value;
this.setState({
userAnswers: newArray
});
}
displayResultsHandler = () => {
var counter = 0;
for(let i = 0; i < this.state.correctAnswers.length; i++) {
if(this.state.correctAnswers[i] === this.state.userAnswers[i]) {
counter = counter+1;
}
}
this.setState({
score: counter
});
console.log("counter: " + counter);
console.log("score: " + this.state.score); // For some reason, this is always zero
if(this.state.score < 5) {
alert("You're dumb asf. Please leave");
} else {
alert("Welcome to NASA");
}
}
render() {
// var userAnswers;
// console.log(userAnswers); How do I pass this as a prop? this.userAnswers? nope. Therefore it has to be a state
console.log("User Answers are: " + this.state.userAnswers);
return (
<div className="App">
<div className="container">
<Title/>
<h2>Only the most genius of individuals will pass</h2>
<hr/>
<Question
correctAnswers={this.state.correctAnswers}
updateUserAnswersHandler={this.updateUserAnswersHandler}
userAnswers={this.state.userAnswers}
questionArray={this.state.questionArray}
answerChoicesArray={this.state.answerChoicesArray} />
<SubmitButton
clicked = {this.displayResultsHandler} />
</div>
</div>
);
}
}
export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
答案 0 :(得分:2)
状态更新是异步。您对setState
的呼叫只会使更新排队,而不会立即进行。
您还使用了错误的setState
重载(您并不孤单,很多人都这样做!)。根据现有状态设置新状态时,不能使用仅接受对象的版本。您必须使用回调版本。如果要在完成后使用结果状态,则可以传递第二个函数,状态更新完成后将调用该函数:
displayResultsHandler = () => {
this.setState(
// Updater
prevState => {
var counter = 0;
for(let i = 0; i < prevState.correctAnswers.length; i++) {
if(prevState.correctAnswers[i] === prevState.userAnswers[i]) {
counter = counter+1;
}
}
return {score: counter};
},
// Completion callback
() => {
console.log("score: " + this.state.score);
}
);
};
但是,文档说明了有关使用完成回调的信息:
通常,我们建议使用
componentDidUpdate()
代替这种逻辑。
文档this page和setState
API docs中都有这些内容。
作为一个旁注,一些高级JavaScript功能(解构和简写属性表示法)和一个普通的功能(增量运算符)可以使该代码更加简洁:
displayResultsHandler = () => {
this.setState(
// Updater
({correctAnswers, userAnswers}) => { // *** Destructuring
let score = 0;
for (let i = 0; i < correctAnswers.length; i++) {
if (correctAnswers[i] === userAnswers[i]) {
++score; // *** Increment
}
}
return {score}; // *** Shorthand property
},
// Completion callback
() => {
console.log("score: " + this.state.score);
}
);
};
有些人甚至可以使用reduce
而不是for
循环;我不相信可读性不会受到影响,但是:
displayResultsHandler = () => {
this.setState(
// Updater
({correctAnswers, userAnswers}) => ({
score: correctAnswers.reduce(
(score, answer, index) =>
score + (answer === userAnswers[index] ? 1 : 0),
0
)
}),
// Completion callback
() => {
console.log("score: " + this.state.score);
}
);
};
(您甚至可以删除条件运算符,而仅使用score + (answer === userAnswers[index])
,因为true
强制为1
,false
强制为0
,但是... )
答案 1 :(得分:0)
this.setState是一个异步函数。
尝试-
this.setState({
score: counter
},function(){
console.log(this.state.score)
})