我正在制作一个测验页面,测验完成后,我将显示所有正确答案。为了显示答案,我正在列出一个列表并添加所有问题并在列表中更正并呈现列表,但我得到了重复的答案我不知道问题是什么,请帮助。
截图 => https://ibb.co/RPz862t
import React from "react";
type Props = {
questions: string | any[];
};
const items: any[] = [];
const iterateQ = (question:string | any[]) => {
let a = 0;
let size = question.length;
while(a < size) {
items.push(
<div>
<div className="font-normal">
Question No: {a}
</div>
<div className="font-bold">
{question[a].question}
</div>
<div className="bg-green-300 font-bold font-color p-1 rounded-lg shadow-lg w-full mt-2">
{question[a].answer[question[a].correctAnswer].answerText}
</div>
</div>
);
a = a + 1;
}
return items;
}
const ShowAns: React.FC<Props> = ({
questions,
}) => (
<>
<div className="justify-center items-center">
{iterateQ(questions)}
</div>
</>
);
export default ShowAns;
答案 0 :(得分:1)
试试这个代码
import React from "react";
type Props = {
questions: string | any[];
};
// const items: any[] = []; <==== remove this
const iterateQ = (question:string | any[]) => {
let a = 0;
let size = question.length;
const items: any[] = [] // <==== declare here, so every time function is called, it will be a new array.
while(a < size) {
items.push(
<div>
<div className="font-normal">
Question No: {a}
</div>
<div className="font-bold">
{question[a].question}
</div>
<div className="bg-green-300 font-bold font-color p-1 rounded-lg shadow-lg w-full mt-2">
{question[a].answer[question[a].correctAnswer].answerText}
</div>
</div>
);
a = a + 1;
}
return items;
}
const ShowAns: React.FC<Props> = ({
questions,
}) => (
<>
<div className="justify-center items-center">
{iterateQ(questions)}
</div>
</>
);
export default ShowAns;