React 中带有输入的异步状态
Posted
技术标签:
【中文标题】React 中带有输入的异步状态【英文标题】:Asynchronous state with input in react 【发布时间】: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;
【问题讨论】:
【参考方案1】:确实setState()
方法是异步的,不会总是立即更新。
但是要修复您的验证,只需将单词与当前输入进行比较,而不是当前状态下的答案:
validate = (e) =>
e.preventDefault()
const answer = e.target.value
this.setState( currentAnswer: answer)
if (answer === this.state.currentWord.anglais)
this.setState(correctAnswer : true)
【讨论】:
以上是关于React 中带有输入的异步状态的主要内容,如果未能解决你的问题,请参考以下文章
React Native 中带有 React Hooks 的基本全局状态