reactjs onClick事件无法正常工作,如何修复?

kq4fsx7k  于 2022-11-22  发布在  React
关注(0)|答案(1)|浏览(140)

我构建了一个react组件,用来玩一个抽认卡游戏。每当用户点击check按钮时,应用程序都会检查答案是否正确。然而,有时我点击按钮却什么也没发生。我不知道为什么。
下面是组件源代码:

import React, { useEffect, useState } from "react";
import Flashcard from "../Flashcard/Flashcard";
import quiz from "./quiz.css"

const Quiz = () => {
    const [answer, setAnswer] = useState('');
    const [index, setIndex] = useState(0);
    const [quiz, setQuiz] = useState({ Flashcards: [{word: '', translation: '', id: 0}], Title: '', id: '' })
    const [correctAnswers, setCorrectAnswers] = useState([]);

    useEffect(() => {
        if (localStorage.getItem("currentQuiz") !== null) {
            setQuiz(JSON.parse(localStorage.getItem("currentQuiz")));
            setIndex(Math.floor(Math.random() * quiz.Flashcards.length));
        }
    }, [])

    const onAnswerChange = (event) => {
        setAnswer(event.target.value);
    }

    const check = () => {
        if(quiz.Flashcards[index].translation === answer) {
            correctAnswers.push(quiz.Flashcards[index]);
            setCorrectAnswers(correctAnswers);
            if (quiz.Flashcards.length > 1){
                quiz.Flashcards.splice(index, 1);
                setIndex(Math.floor(Math.random() * quiz.Flashcards.length));
            }
        }
        else {
            setIndex(Math.floor(Math.random() * quiz.Flashcards.length));
        }
    }

    return (
        <div className="quiz">
            <div className="quiz-top">
                <button>Reset</button>
                <p className="quiz-p">{`${correctAnswers.length}/${correctAnswers.length + quiz.Flashcards.length}`}</p>
            </div>
            <div className="quiz-middle">
                <div className="flashcard-wrapper">
                    <div className="flashcard-top">
                        <p>{quiz.Title}</p>
                        <p>like</p>
                    </div>
                    <div className="flashcard-middle">
                        <p>{quiz.Flashcards[index].word}</p>
                    </div>
                    <div className="flashcard-bottom">
                        <input type="text" placeholder="Answer.. " value={answer} onChange={event => onAnswerChange(event)} />
                    </div>
                </div>
            </div>
            <div className="quiz-bottom">
                <button onClick={check} >Check!</button>
            </div>
        </div>
    )
}

export default Quiz;

This is the UI of the component
老实说,我不知道是什么导致了这个问题。

zwghvu4y

zwghvu4y1#

看起来不是使用setQuiz函数修改状态导致了这个问题。只是添加了这个函数,它就起作用了。
添加了答案,以防任何人有类似的问题。

相关问题