我想在满足handleAnswerClick()函数中的条件后将quizFinished的usestate更改为true。这是下面的代码:
注意:我正在学习Codedamn react 18视频29的反应
import React, { useState } from 'react'
export default function App() {
// Define a state variable here to track question status
const [quizFinished, setQuizFinished] = useState(false)
const [currentIndex, setCurrentIndex] = useState(0)
function handleAnswerClick() {
// Check if the quiz is over here
if (currentIndex === questions.length) {
setQuizFinished(quizFinished=true)
}
else {
setCurrentIndex(currentIndex + 1);
}
// If yes, set the quizFinished variable to true
// If no, increment the current index like always
}
```
Their is some HTML code below that is in the tutorial. The Tutorial is free.
将true
传递给setQuizFinished
:
setQuizFinished(true)
然而,由于quizFinished
是由currentIndex
导出的,使用状态是多余的。只需在每次渲染时计算它:
export default function App() {
const [currentIndex, setCurrentIndex] = useState(0)
const quizFinished = currentIndex === questions.length
function handleAnswerClick() {
if(!quizFinished) {
setCurrentIndex(currentIndex => currentIndex + 1);
)
}
1。只需将true传递给setQuizFinished2.检查currentIndex == questions.length-1的条件