如何将获取的数据放入州?

发布于 2025-02-10 18:36:29 字数 362 浏览 0 评论 0原文


我试图将获取的数据放入州,但它不起作用,请让我知道我在这里做错了什么,我也希望特定的数据像在此示例中一样,我只想要问题,答案和不正确答案,我也想将整个数据放入对象的数组中

const [quiz,setQuiz]=useState({});

useEffect(()=>{
  const  getQuizData =async ()=>{
  const res = await fetch("https://opentdb.com/api.php?amount=10")
  const data = await res.json();
  setQuiz({data});
  }
  getQuizData();


},[])

I am trying to put fetched data into the state but it's not working, please let me know what I am doing wrong here, and also I want specific data to be inside the state like in this example I want only questions, answers, and incorrect answer, also I wanted to put the whole data into the array of object

const [quiz,setQuiz]=useState({});

useEffect(()=>{
  const  getQuizData =async ()=>{
  const res = await fetch("https://opentdb.com/api.php?amount=10")
  const data = await res.json();
  setQuiz({data});
  }
  getQuizData();


},[])

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

山田美奈子 2025-02-17 18:36:29

来自您的数据的内容如下。我怀疑您想要的是setquiz(data. recults),例如usestate([])也应该有所帮助。

const data = {
  response_code: 0,
  results: [
    {
      category: 'History',
      type: 'multiple',
      difficulty: 'medium',
      question: 'Joseph Smith was the founder of what religion?',
      correct_answer: 'Mormonism',
      incorrect_answers: ['Buddhism', 'Christianity', 'Hinduism'],
    },
    {
      category: 'Sports',
      type: 'multiple',
      difficulty: 'medium',
      question: 'In a game of snooker, what colour ball is worth 3 points?',
      correct_answer: 'Green',
      incorrect_answers: ['Yellow', 'Brown', 'Blue'],
    },
  ],
};

what coming from your data is below. I suspect what you want is setQuiz(data.results) also initializing like useState([]) should help too.

const data = {
  response_code: 0,
  results: [
    {
      category: 'History',
      type: 'multiple',
      difficulty: 'medium',
      question: 'Joseph Smith was the founder of what religion?',
      correct_answer: 'Mormonism',
      incorrect_answers: ['Buddhism', 'Christianity', 'Hinduism'],
    },
    {
      category: 'Sports',
      type: 'multiple',
      difficulty: 'medium',
      question: 'In a game of snooker, what colour ball is worth 3 points?',
      correct_answer: 'Green',
      incorrect_answers: ['Yellow', 'Brown', 'Blue'],
    },
  ],
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文