【发布时间】:2021-02-20 18:12:37
【问题描述】:
我正在开发一个简单的测验应用程序。我有一个本地数组,其中包含每次随机顺序的问题。每次运行 handleAnswerOptionClick 时都会触发以不同顺序打乱数组的函数。
怎样才能运行一次arrayShuffle函数?
我的猜测是我可以为此使用 useEffect,但我还没有让它工作。它抱怨它没有不同的依赖关系。
useEffect(() => {
arrayShuffle(questions);
}, []);
代码:CodeSandox
测验容器:
import React, { useState, useEffect } from "react";
export const QuizContainer = () => {
const questions = [
{
questionText: "What is the capital of France?",
answerOptions: [
{ option: "New York", isCorrect: false },
{ option: "London", isCorrect: false },
{ option: "Paris", isCorrect: true },
{ option: "Dublin", isCorrect: false }
]
},
{
questionText: "Who is CEO of Tesla?",
answerOptions: [
{ option: "Jeff Bezos", isCorrect: false },
{ option: "Elon Musk", isCorrect: true },
{ option: "Bill Gates", isCorrect: false },
{ option: "Tony Stark", isCorrect: false }
]
},
{
questionText: "The iPhone was created by which company?",
answerOptions: [
{ option: "Apple", isCorrect: true },
{ option: "Intel", isCorrect: false },
{ option: "Amazon", isCorrect: false },
{ option: "Microsoft", isCorrect: false }
]
},
{
questionText: "How many Harry Potter books are there?",
answerOptions: [
{ option: "1", isCorrect: false },
{ option: "4", isCorrect: false },
{ option: "6", isCorrect: false },
{ option: "7", isCorrect: true }
]
}
];
const [currentQuestion, setCurrentQuestion] = useState(0);
const [showScore, setShowScore] = useState(false);
const [score, setScore] = useState(0);
// Event handlers
const handleAnswerOptionClick = (isCorrect) => {
if (isCorrect) {
setScore(score + 1);
}
const nextQuestion = currentQuestion + 1;
nextQuestion < questions.length
? setCurrentQuestion(nextQuestion)
: setShowScore(true);
};
// ShuffleArray
const arrayShuffle = function (arr) {
let newPos, temp;
for (let i = arr.length - 1; i > 0; i--) {
newPos = Math.floor(Math.random() * (i + 1));
temp = arr[i];
arr[i] = arr[newPos];
arr[newPos] = temp;
}
return arr;
};
const newArray = arrayShuffle(questions);
console.log(newArray);
return (
<>
<h1>QuizContainer</h1>
{showScore ? (
<p>
You scored {score} out of {questions.length}
</p>
) : (
<>
<p>
Question {currentQuestion + 1}/{questions.length}
</p>
<p>{questions[currentQuestion].questionText}</p>
<div>
{questions[currentQuestion].answerOptions.map(
(answerOption, index) => (
<div key={index}>
<button
onClick={() =>
handleAnswerOptionClick(answerOption.isCorrect)
}
>
{answerOption.option}
</button>
</div>
)
)}
</div>
</>
)}
</>
);
};
请问我是否需要澄清,以及你们是否认为我的处理方式正确。
先谢谢了,
埃里克
【问题讨论】:
标签: javascript reactjs ecmascript-6 react-hooks