reactjs 我如何将一个布尔值添加到从React中的API获取的数组?[duplicate]

oxf4rvwz  于 2023-02-03  发布在  React
关注(0)|答案(1)|浏览(98)
    • 此问题在此处已有答案**:

Add property to an array of objects(7个答案)
十小时前关门了。
我使起始代码运行良好。您可以在这里查看https://github.com/msaikat022/Quizzical。问题是我想添加一个名为isHeld的字段来存储API返回的数组中的布尔值,该数组通过useState设置为array以呈现测验问题。这是为了确保如果isHeld为真,这个选项会改变它的背景颜色,反之亦然。2这个功能我会进一步添加,但在此之前,我需要布尔值。3请帮助,如果你可以。

import { useEffect, useState } from "react";
    import Question from "./Question";
    import memeData from "../memeData";

    export default function Quiz() {
      //array rendering function
      function getQuestions() {
        const f = memeData.results;
        const arr = [];
        for (let i = 0; i < 5; i++) {
          arr.push({
            id: f[i].id,
            category: f[i].category,
            type: f[i].type,
            difficulty: f[i].difficulty,
            question: f[i].question,
            correct_answer: f[i].correct_answer,
            incorrect_answers: f[i].incorrect_answers,
            isHeld: false,
          });
        }
        return arr;
      }

      //state for creating array of questions
      const [qArray, setqArray] = useState(getQuestions());

      console.log(qArray);

      //useeffect for fetching data from api
      useEffect(() => {
        fetch(
          "https://opentdb.com/api.php?amount=5&category=9&difficulty=easy&type=multiple"
        )
          .then((res) => res.json())
          .then((data) => {
            const arr = data.results;
            setqArray(arr);
          });
      }, []);

      console.log(qArray);
      //mapping over array
      const finalArray = qArray.map((item) => {
        return (
          <Question
            key={item.id}
            question={item.question}
            correct_answer={item.correct_answer}
            incorrect_answers={item.incorrect_answers}
          />
        );
      });

      return <main>{finalArray}</main>;
    }

我尝试在useEffect代码下面添加此代码:

setqArray((prevArr) =>
    prevArr.map((item) => {
      return {
        ...item,
        isHeld: false,
      };
    })
    );

但这会产生错误-未捕获错误:重新呈现次数过多。React限制呈现次数以防止无限循环。

s1ag04yj

s1ag04yj1#

在useEffect中,你可以添加下面的代码,它会将isHeld属性添加到api响应的数组中,然后设置usestate。

useEffect(() => {
    fetch(
      "https://opentdb.com/api.php?amount=5&category=9&difficulty=easy&type=multiple"
    )
      .then((res) => res.json())
      .then((data) => {
        const arr = data.results;
        arr.forEach((object)=>{
          object["isHeld"] = false;
        })
        setqArray(arr);
      });
  }, []);

希望能有所帮助

相关问题