如何将数组数据映射到React中的表行

huangapple go评论62阅读模式
英文:

How to map array data into table row in React

问题

我只会为您翻译代码部分,不包括问题的回答。以下是代码的翻译部分:

import { useEffect, useState } from 'react';
import './App.css';

function Countries() {
  const [data, setData] = useState([]);
  useEffect(() => {
    fetch('https://restcountries.com/v3.1/all?fields=name,continents,population,flag')
      .then((resp) => resp.json())
      .then((apiData) => {
        setData(apiData);
      });
  });
  return (
    <div className="app-container">
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Continent</th>
            <th>Population</th>
            <th>Flag</th>
          </tr>
        </thead>
        <tbody>
          {data.map((country) => (
            <tr key={country.name}>
              <td>{country.name}</td>
              <td>{country.continents}</td>
              <td>{country.population}</td>
              <td>{country.flag}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default Countries;

希望这可以帮助您的React项目从API获取数据并在表格中显示数据。

英文:

I'm just trying to implement a simple React project that retrieves data from an API and iterates over it to create table rows. I'm not getting any errors, but the data isn't appearing in the table.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

import { useEffect, useState } from &#39;react&#39;;
import &#39;./App.css&#39;;

function Countries() {
  const [data, setData] = useState([]);
  useEffect(() =&gt; {
    fetch(&#39;https://restcountries.com/v3.1/all?fields=name,continents,population,flag&#39;)
      .then((resp) =&gt; resp.json())
      .then((apiData) =&gt; {
        setData(apiData);
      });
  });
  return (
    &lt;div className=&quot;app-container&quot;&gt;
      &lt;table&gt;
        &lt;thead&gt;
          &lt;tr&gt;
            &lt;th&gt;Name&lt;/th&gt;
            &lt;th&gt;Continent&lt;/th&gt;
            &lt;th&gt;Population&lt;/th&gt;
            &lt;th&gt;Flag&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;tbody&gt;
          {data.map((country) =&gt; {
            &lt;tr&gt;
              &lt;td&gt;{country.name}&lt;/td&gt;
              &lt;td&gt;{country.continents}&lt;/td&gt;
              &lt;td&gt;{country.population}&lt;/td&gt;
              &lt;td&gt;{country.flag}&lt;/td&gt;
            &lt;/tr&gt;
          })}
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;
  );
}

export default Countries;

<!-- end snippet -->

The data is being fetched:
如何将数组数据映射到React中的表行

Still there are no errors so I'm not sure why the data isn't appearing in the table.
Just returns a blank page.
如何将数组数据映射到React中的表行

Any help would be greatly appreciated.

答案1

得分: 1

你在tbody标签内的map函数中没有返回任何内容。你需要添加return关键字或使用括号来包裹JSX。同时,将空数组作为useEffect的第二个参数,以便只运行一次。

import { useEffect, useState } from 'react';
import './App.css';

function Countries() {
  const [data, setData] = useState([]);
  useEffect(() => {
    fetch('https://restcountries.com/v3.1/all?fields=name,continents,population,flag')
      .then((resp) => resp.json())
      .then((apiData) => {
        setData(apiData);
      });
  }, []); // 空数组在这里
  return (
    <div className="app-container">
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Continent</th>
            <th>Population</th>
            <th>Flag</th>
          </tr>
        </thead>
        <tbody>
          {data.map((country) => (
            <tr key={country.name}>
              <td>{country.name}</td>
              <td>{country.continents}</td>
              <td>{country.population}</td>
              <td>{country.flag}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default Countries;
英文:

You're not returning anything from the map function inside the tbody tag. You need to add the return keyword or use parentheses to wrap the JSX. Also pass an empty array as the second argument to run useEffect only once.

import { useEffect, useState } from &#39;react&#39;;
import &#39;./App.css&#39;;

function Countries() {
  const [data, setData] = useState([]);
  useEffect(() =&gt; {
    fetch(&#39;https://restcountries.com/v3.1/all?fields=name,continents,population,flag&#39;)
      .then((resp) =&gt; resp.json())
      .then((apiData) =&gt; {
        setData(apiData);
      });
  }, []); // empty array here
  return (
    &lt;div className=&quot;app-container&quot;&gt;
      &lt;table&gt;
        &lt;thead&gt;
          &lt;tr&gt;
            &lt;th&gt;Name&lt;/th&gt;
            &lt;th&gt;Continent&lt;/th&gt;
            &lt;th&gt;Population&lt;/th&gt;
            &lt;th&gt;Flag&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;tbody&gt;
          {data.map((country) =&gt; (
            &lt;tr&gt;
              &lt;td&gt;{country.name}&lt;/td&gt;
              &lt;td&gt;{country.continents}&lt;/td&gt;
              &lt;td&gt;{country.population}&lt;/td&gt;
              &lt;td&gt;{country.flag}&lt;/td&gt;
            &lt;/tr&gt;
          ))}
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;
  );
}

export default Countries;

答案2

得分: 1

以下是翻译好的部分:

你没有返回渲染的 `tr` 元素因为你用花括号包裹它们而不是用圆括号此外`name` 是一个对象你应该使用 `country.name.common` `country.continents` 是一个数组你应该将它连接成一个单独的字符串或者迭代这些项目

```jsx
{data.map(country => (
  <tr key={country.flag}>
    <td>{country.name.common}</td>
    <td>{country.continents.join(', ')}</td>
    <td>{country.population}</td>
    <td>{country.flag}</td>
  </tr>
))}

此外,你的 useEffect 没有依赖数组,这意味着它会在每个状态改变时运行(比如设置状态),这将导致另一个 API 调用和设置状态,从而导致无限循环。将一个空数组 [] 设置为你的 useEffect 的依赖以防止这种情况发生。

示例

const { useEffect, useState } = React;

function Countries() {
  const [data, setData] = useState([]);
  
  useEffect(() => {
    fetch('https://restcountries.com/v3.1/all?fields=name,continents,population,flag')
      .then(resp => resp.json())
      .then(apiData => {
        setData(apiData);
      });
  }, []);
  
  return (
    <div className="app-container">
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Continent</th>
            <th>Population</th>
            <th>Flag</th>
          </tr>
        </thead>
        <tbody>
          {data.map(country => (
            <tr key={country.flag}>
              <td>{country.name.common}</td>
              <td>{country.continents.join(', ')}</td>
              <td>{country.population}</td>
              <td>{country.flag}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

ReactDOM
  .createRoot(root)
  .render(<Countries />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

<div id="root"></div>
英文:

You are not returning the render tr elements, because you wrapped them in curly brackets instead of parentheses. In addition, name is an object, and you should use country.name.common, and country.continents is an array, and you should join it to a single string, or iterate the items:

  {data.map(country =&gt; (
    &lt;tr key={country.flag}&gt;
      &lt;td&gt;{country.name.common}&lt;/td&gt;
      &lt;td&gt;{country.continents.join(&#39;, &#39;)}&lt;/td&gt;
      &lt;td&gt;{country.population}&lt;/td&gt;
      &lt;td&gt;{country.flag}&lt;/td&gt;
    &lt;/tr&gt;
  ))}

In addition, you the useEffect doesn't have a dependencies array, which means that it would run on every state change (like setting the state), which would cause another api calls, and set state, which would lead to an infinite loop. Set an empty array [] as the dependencies of your useEffect to prevent this.

Example:

<!-- begin snippet: js hide: true console: true babel: true -->

<!-- language: lang-js -->

const { useEffect, useState } = React;


function Countries() {
  const [data, setData] = useState([]);
  
  useEffect(() =&gt; {
    fetch(&#39;https://restcountries.com/v3.1/all?fields=name,continents,population,flag&#39;)
      .then((resp) =&gt; resp.json())
      .then((apiData) =&gt; {
        setData(apiData);
      });
  }, []);
  
  return (
    &lt;div className=&quot;app-container&quot;&gt;
      &lt;table&gt;
        &lt;thead&gt;
          &lt;tr&gt;
            &lt;th&gt;Name&lt;/th&gt;
            &lt;th&gt;Continent&lt;/th&gt;
            &lt;th&gt;Population&lt;/th&gt;
            &lt;th&gt;Flag&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;tbody&gt;
          {data.map(country =&gt; (
            &lt;tr key={country.flag}&gt;
              &lt;td&gt;{country.name.common}&lt;/td&gt;
              &lt;td&gt;{country.continents.join(&#39;, &#39;)}&lt;/td&gt;
              &lt;td&gt;{country.population}&lt;/td&gt;
              &lt;td&gt;{country.flag}&lt;/td&gt;
            &lt;/tr&gt;
          ))}
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;
  );
}

ReactDOM
  .createRoot(root)
  .render(&lt;Countries /&gt;);

<!-- language: lang-html -->

&lt;script crossorigin src=&quot;https://unpkg.com/react@18/umd/react.development.js&quot;&gt;&lt;/script&gt;
&lt;script crossorigin src=&quot;https://unpkg.com/react-dom@18/umd/react-dom.development.js&quot;&gt;&lt;/script&gt;

&lt;div id=&quot;root&quot;&gt;&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月7日 02:58:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75654780.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定