reactjs 如何访问嵌套数组中的属性?

ao218c7q  于 2022-12-18  发布在  React
关注(0)|答案(3)|浏览(174)

我已经制作了一个API,其中包含我能够获取的测验问题,现在我尝试呈现“questions”数组中的单个属性(“clue1”)。
这是我的代码:

export const SingleClue = () => {
  const [questions, setQuestions] = useState({})

  const fetchData = () => {
    fetch('https://final-project-api-veooltntuq-lz.a.run.app/questions')
      .then((response) => {
        return response.json()
      })
      .then((data) => {
        setQuestions(data)
      })
  }

  useEffect(() => {
    fetchData()
  }, [])

  return (
    <div>
      <div>
        {questions.map((question) => (
          <div key={id}>
            {question.questions.map((clue) => (
              <div key={id}>
                <h2>{clue.clue1}</h2>
              </div>
            ))}
          </div>
        ))}
      </div>

    </div>
  )
}

我尝试了不同类型的Map,但似乎没有什么工作。我错过了什么?

5cg8jx4n

5cg8jx4n1#

import { useState, useEffect } from 'react';
import * as React from 'react';

const App: React.FC = () => {
  const [questions, setQuestions] = useState([]);//FIX 1 -> make default state array

  const fetchData = () => {
    fetch('https://final-project-api-veooltntuq-lz.a.run.app/questions')
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        console.log(data);
        setQuestions(data.questions);//FIX 2-> set response.questions as state
      });
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div>
      <div>
        {questions.map((question, id) => (
          <div key={id}>
            //FIX 3 -> No need to iterate here.
              <div key={id}>
                <h2>{question.clue1}</h2>
              </div>
            
          </div>
        ))}
      </div>
    </div>
  );
};

export default App;
vvppvyoh

vvppvyoh2#

您可以直接访问该属性,如下所示:

return (
  <div>
    <h2>{questions.clue1}</h2>
  </div>
)

或者,如果您想要呈现“questions”数组中的多个属性,您可以使用map函数来遍历数组并呈现每个元素。

return (
  <div>
    {questions.map((question) => (
      <div key={question.id}>
        <h2>{question.clue1}</h2>
        <p>{question.clue2}</p>
      </div>
    ))}
  </div>
)

这将呈现“questions”数组中每个元素的“clue1”和“clue2”属性。

kgsdhlau

kgsdhlau3#

您的API不会返回嵌套数组,而是返回一个对象,其中包含一个位于关键字“questions”处的对象数组:

{
"success": true,

"questions": [

{
"_id": "639da067623ef25e001fbe63",
"id": 2,
"clue1": "The city we are looking for is home to one of the world’s largest Jewish populations outside of Israel.",
"clue1ImgUrl": "",
"clue2": "Our city is one of the few global cities with a permanent commission of the International Olympic Committee.",
"clue2ImgUrl": "",
"clue3": "This city has a rich cultural life, with a wide variety of museums, galleries, and performance venues and it is home to the world’s largest tango festival.",
"clue3ImgUrl": "",
"clue4": "It is located on the western shore of the Rio de la Plata estuary and is a major financial and cultural hub in Latin America.",
"clue4ImgUrl": "",
"clue5": "This is the capital and largest city of Argentina.",
"clue5ImgUrl": "",
"correctAnswer": "Buenos Aires",
"correctAnswerImgUrl": "",
"__v": 0
},

{
"_id": "639da067623ef25e001fbe62",
"id": 1,
"clue1": "The city we are looking for has a color-coded public transport system, which consists of five metro lines, 24 tram lines, and over 100 bus lines.",
"clue1ImgUrl": "https://www.mapillary.com/embed?map_style=Mapillary%20streets&image_key=248871873647204&style=photo",
"clue2": "Our city is considered to be the most livable city in the world due to its low crime rate and high quality of life.",
"clue2ImgUrl": "https://www.mapillary.com/embed?map_style=Mapillary%20streets&image_key=2871879196357526&style=photo",
"clue3": "In this city you can find the oldest continuously operating cafe in the world, Cafe Central, which has been open since 1876.",
"clue3ImgUrl": "https://www.mapillary.com/embed?map_style=Mapillary%20streets&image_key=1291397584588099&style=photo",
"clue4": "It is the birthplace of several famous composers such as Wolfgang Amadeus Mozart and Ludwig van Beethoven and the city is the birthplace of the waltz.",
"clue4ImgUrl": "https://www.mapillary.com/embed?map_style=Mapillary%20streets&image_key=510338956979705&style=photo",
"clue5": "This is the capital of Austria and it is known for its beautiful imperial palaces and architecture.",
"clue5ImgUrl": "https://www.mapillary.com/embed?map_style=Mapillary%20streets&image_key=187157113226910&style=photo",
"correctAnswer": "Vienna",
"correctAnswerImgUrl": "https://www.mapillary.com/embed?map_style=Mapillary%20streets&image_key=625621858834998&style=photo",
"__v": 0

}
]
}

如果您使用fetch,则需要将json响应传递给state,如下所示:

const fetchData = () => {
fetch("https://final-project-api-veooltntuq-lz.a.run.app/questions").then(
  (response) => {
    response.json().then((jsonData) => {
      setQuestions(jsonData.questions);
    });
  }
);

};
......但我会使用axios和一个异步函数,如下所示:

const fetchData = async () => {
try {
  const response = await axios.get(
    "https://final-project-api-veooltntuq-lz.a.run.app/questions"
  );
  setQuestions(response.data.questions);
} catch (error) {
  console.log(error);
}


};
这将为两个问题提供线索1:

{questions.map((question) => {
    return <div key={question.id}>{question.clue1}</div>;
  })}

相关问题