1 回答
TA贡献1951条经验 获得超3个赞
想法:主要想法是在 API 调用中获取 Questions 数组,并确保在那里随机获取 5 个问题。我的做法是,一旦我从 API 调用接收到数据,我就会执行promise chaining
并处理所有代码,以在另一个then()
块中获取 5 个随机问题。当我收到 5 个随机问题时,我将状态保存为currentQues
.
import React, { useState, useEffect } from "react";
import "./App.css";
function App() {
const [currentQues, setcurrentQues] = useState([]);
//importing ques using api
useEffect(() => {
selectingQues();
}, []);
// selecting 5 ques at random for our quiz
const selectingQues = async () => {
const response = await fetch(
"https://opentdb.com/api.php?amount=20&category=18&difficulty=medium&type=multiple"
);
const data = await response.json();
console.log(data);
const initialQuestions = data.results;
let curr = [];
// console.log(initialQuestions.length);
let length = initialQuestions.length;
for (let i = 0; i < 5; i++) {
let selector = Math.floor(Math.random() * length);
curr[i] = initialQuestions[selector];
}
setcurrentQues(curr);
};
return (
<div className="App">
{currentQues.length > 0 && <Question currentQuestions={currentQues} />}
</div>
);
}
export default App;
const Question = ({ currentQuestions }) => {
// const { question, correct_answer } = question;
console.log(currentQuestions);
return (
<>
{currentQuestions.map((question) => (
<div key={question.question}>
<p>
<strong>Question:</strong> {question.question}
</p>
<p>
<strong>Answer:</strong> {question["correct_answer"]}
</p>
</div>
))}
</>
);
};
添加回答
举报