我想弄清楚为什么我的函数无法从 useState 钩子中读取值。我现在在我的 verifyAnswer 函数中正确更新了“questionIndex”的 useState 值,但我无法确定为什么函数“renderQuestion”不知道 questionIndex 的值正在更新。
我没有收到任何错误消息,并且控制台记录了输出。 questionIndex 按预期更新,但 renderQuestion 函数根本没有更新。
之前我尝试使用 useEffect 并且它工作正常,但是代码有点乱。现在我再次猜测我对 React 的总体理解,因为代码看起来应该可以正常工作,而我在寻找解决方案的过程中迷失了方向。
代码:
const [questionIndex, setQuestionIndex] = useState(0)
function renderQuestion() {
console.log(`questionIndex from render question function is : ${questionIndex}`)
setWordToTranslate(Data[questionIndex].word);
setAnswer(Data[questionIndex].translation)
}
function verifyAnswer(value) {
if (value === answer) {
console.log("answer is correct!");
if (questionIndex < questionsLength) {
setQuestionIndex(questionIndex + 1)
renderQuestion()
}
}
}
function handleInputChange(event) {
const {value} = event.target;
setUserInput(value);
verifyAnswer(value);
}
答案 0 :(得分:0)
setState 是异步的。
我认为你应该在 useEffect 中处理 renderQuestion
const [questionIndex, setQuestionIndex] = useState(0)
function renderQuestion() {
console.log(`questionIndex from render question function is : ${questionIndex}`)
setWordToTranslate(Data[questionIndex].word);
setAnswer(Data[questionIndex].translation)
}
useEffect(() => {
renderQuestion()
}, [questionIndex])
function verifyAnswer(value) {
if (value === answer) {
console.log("answer is correct!");
if (questionIndex < questionsLength) {
setQuestionIndex(questionIndex + 1)
}
}
}
function handleInputChange(event) {
const {value} = event.target;
setUserInput(value);
verifyAnswer(value);
}