繁体   English   中英

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

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

概述:

我正在尝试使用 React 显示来自 API 的数据。 我有我需要的“积木”,但我正在努力弄清楚如何将它们结合起来。

问题:

我有一个被渲染的页面,一个从 API 请求数据的 fetch 调用,以及一些循环通过返回的 object 的代码。

我如何将这三件事结合起来,以便我可以看到页面上呈现的内容?

谢谢!

这是我的反应代码:

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

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

export default Index;

以下是我从 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));
}

这是我如何循环通过 object:

var i;

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

您需要在组件渲染时调用端点,但仅在第一次时,如果发生其他渲染,您通常不想继续调用 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;

每当其中一个依赖项发生变化时,钩子useEffect运行,在这种情况下,存在 cero 依赖项,因此这个钩子只会运行一次? 你怎么知道没有依赖关系?

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 .

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>
  );
}

首先,您需要使用useState挂钩初始化本地 state。 在服务器响应之后,您需要将响应设置为本地 state 以便您可以在组件上使用它。

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

鉴于data是一个数组,只要 API 响应,数据就会分配给本地 state,然后使用map您可以循环数组并为每个项目呈现段落或任何其他组件。

您需要确保为循环中的每个元素设置一个key ,这会告诉您在键更改时对挂载/卸载组件做出反应等等。

祝你好运!

暂无
暂无

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

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