【发布时间】:2020-07-18 13:41:30
【问题描述】:
我的状态有问题,每次都迟到。该应用程序包括检查您的英语或法语词汇量,但我遇到了一个问题,即状态 currentAnswer 总是迟到一个字符和句子“正确!”仅当我再写一个字符时才显示。我无法解决问题。我能猜到的是状态不是异步的,但我不能让它异步。有什么想法吗?
import React from 'react';
import './App.css';
class App extends React.Component {
constructor() {
super();
this.state = {
words: [
{
francais: 'bonjour',
anglais: 'hello',
},
{
francais: 'manger',
anglais: 'eat',
},
{
francais: 'avoir',
anglais: 'have',
},
{
francais: 'faire',
anglais: 'do',
},
{
francais: 'jouer',
anglais: 'play',
}
],
key: -1.4,
currentWord: '',
currentAnswer: '',
correctAnswer: false,
giveUp: false,
currentScore: 0,
scoreTotal: 0
}
}
generateWord = () => {
let index = Math.floor(Math.random() * (this.state.words.length + 1))
if(index === this.state.key) {
this.generateWord()
}
this.setState({currentWord: this.state.words[index]})
this.setState({key: index})
}
validate = (e) => {
e.preventDefault()
const answer = e.target.value
this.setState({ currentAnswer: answer})
if (this.state.currentAnswer === this.state.currentWord.anglais) {
this.setState({correctAnswer : true})
}
}
showCorrection = (e) => {
e.preventDefault()
this.setState({giveUp: true})
this.setState({scoreTotal: this.state.scoreTotal + 1})
}
nextWord = (e) => {
e.preventDefault()
this.setState({currentAnswer: ''})
this.setState({ giveUp: false })
this.setState({ correctAnswer: false })
this.generateWord()
if(this.state.correctAnswer) {
this.setState({currentScore: this.state.currentScore + 1})
this.setState({scoreTotal: this.state.scoreTotal + 1})
}
}
componentDidMount() {
this.generateWord()
}
render() {
return (
<div className="App">
<p>Score: {this.state.currentScore}/{this.state.scoreTotal}</p>
<h2 style={{
color: "midnightblue",
fontSize: "50px"
}}>{this.state.currentWord?.francais}</h2>
<form action="">
<input onChange={this.validate} value={this.state.currentAnswer} type="text" placeholder="Entrez la traduction anglaise"/>
<button className="validation" onClick={this.showCorrection}>Give up</button>
<button className="validation" onClick={this.nextWord}>Next</button>
</form>
{this.state.correctAnswer ? <p>Correct !</p> : this.state.giveUp ? <p>La bonne réponse était: {this.state.currentWord?.anglais}</p>: ''}
</div>
)
}
}
export default App;
【问题讨论】:
标签: javascript reactjs asynchronous state