简体   繁体   English

如何在 React 中显示来自 API 的数据

[英]How do I Display Data from an API in React

Overview:概述:

I am trying to use React to display data from an API.我正在尝试使用 React 显示来自 API 的数据。 I have the "building blocks" of what I need, but I am trying to figure out how to combine them.我有我需要的“积木”,但我正在努力弄清楚如何将它们结合起来。

Problem:问题:

I have a page that gets Rendered, a fetch call that requests data from an API, and some code that loops through the returned object.我有一个被渲染的页面,一个从 API 请求数据的 fetch 调用,以及一些循环通过返回的 object 的代码。

How do I combine these three things so that I can see the content rendered on the page?我如何将这三件事结合起来,以便我可以看到页面上呈现的内容?

Thanks!谢谢!

Here is my React code:这是我的反应代码:

import { ... } from "...";

const Index = () => (
  <Page>
    <Frame>
      // HERE IS WHERE I WANT TO LOOP THROUGH THE API RESULTS
    </Frame>
  </Page>
);

export default Index;

Here is how I fetch data from an API:以下是我从 API 获取数据的方法:

function getDataFromApi() {
  var url = "api.example.com";
  return fetch(url, {
    method: "GET",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
  })
  .then((response) => response.json())
  .then((responseData) => {
    return responseData;
  })
  .catch((error) => console.warn(error));
}

Here is how I'm looping through an object:这是我如何循环通过 object:

var i;

for (i = 0; i < objects.length; i++) { 
  var object = objects[i]
  console.log(object);
}

You need to call the endpoint when the component gets rendered, but only the first time, if additional renders happen you usually don't want to keep calling the API.您需要在组件渲染时调用端点,但仅在第一次时,如果发生其他渲染,您通常不想继续调用 API。

import React, { useEffect } from "react";

const Index = () => {
  useEffect(() => {
    getDataFromApi() // <--- call your API on the first render only
  }, []);

  return (
  <Page>
    <Frame>
      // HERE IS WHERE I WANT TO LOOP THROUGH THE API RESULTS
    </Frame>
  </Page>
  );
}

export default Index;

The hook useEffect runs whenever one of the dependencies changes, in this case there are cero dependencies, therefore this hook will only run once?每当其中一个依赖项发生变化时,钩子useEffect运行,在这种情况下,存在 cero 依赖项,因此这个钩子只会运行一次? How do you know there are no dependencies?你怎么知道没有依赖关系?

useEffect(() => {
   // Your code
}, []); //<---- These are your dependencies, the array is empty, therefore no dependencies for this hook.

The second thing is to store the API response somewhere, we usually use the local state, but you can use a library such as redux, mobox, or something else to store the data, in this example I'm going to use the local state. The second thing is to store the API response somewhere, we usually use the local state, but you can use a library such as redux, mobox, or something else to store the data, in this example I'm going to use the local state .

import React, { useState, useEffect } from "react";

const Index = () => {
  const [data, setData] = useState([]); // <--- Initialize the state with an empty array
  useEffect(() => {
    getDataFromApi()
      .then((response) => setData(response)); // <---- Set the data to the local state
  }, []);

  return (
  <Page>
    <Frame>
      // HERE IS WHERE I WANT TO LOOP THROUGH THE API RESULTS
    </Frame>
  </Page>
  );
}

First you need to initialize the local state by using the useState hook.首先,您需要使用useState挂钩初始化本地 state。 The, after the server response you need to set the response to the local state so you can use it on your component.在服务器响应之后,您需要将响应设置为本地 state 以便您可以在组件上使用它。

return (
  <Page>
    <Frame>
      { data.map((item) =>
         <p key={item.id}>{item.name}</p>
       )}
    </Frame>
  </Page>
  );

Given that data is an array, whenever the API responds the data gets assigned to the local state and then using map you can loop the array and render a paragraph or any other component for each item.鉴于data是一个数组,只要 API 响应,数据就会分配给本地 state,然后使用map您可以循环数组并为每个项目呈现段落或任何其他组件。

You need to make sure to set a key to each element in the loop, this tells react to mount/unmount component if the key changes, among other things.您需要确保为循环中的每个元素设置一个key ,这会告诉您在键更改时对挂载/卸载组件做出反应等等。

Good luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM