获取的数据在React表格中不显示

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

fetching data not showing in table in react

问题

以下是您要的翻译部分:

我正在创建一个表格并使用 Axios 获取数据然而我无法打印数据 - 当我检查时数据在浏览器中已经打印出来但我无法将特定数据打印成表格格式

在我的代码中应该做什么更改

import { useEffect, useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Table } from "react-bootstrap";
import axios from "axios";
export default function App() {
  const [user, setUser] = useState([]);
  useEffect(() => {
    axios
      .get("https://jsonplaceholder.typicode.com/users", (req, res) => {
        res.json();
      })
      .then((data) => setUser({ ...user, data }))
      .catch((error) => console.error(error));
  });

  return (
    <div className="App">
      <h3 className="text-primary">用户列表</h3>
      <Table
        variant="danger"
        striped
        bordered
        hover
        className="shadow-lg text-center"
      >
        <thead>
          <tr>
            <th>id</th>
            <th>姓名</th>
            <th>用户名</th>
            <th>电子邮件</th>
          </tr>
        </thead>
        <tbody>
          {user?.data?.length > 0 &&
            user.data.map((user) => {
              return (
                <tr key={user.id}>
                  <td>{JSON.stringify(user.id)}</td>
                  <td>{JSON.stringify(user.name)}</td>
                  <td>{JSON.stringify(user.username)}</td>
                  <td>{JSON.stringify(user.email)}</td>
                </tr>
              );
            })}
        </tbody>
      </Table>
      {/* <div>{JSON.stringify(user.data)}</div> */}
    </div>
  );
}

请注意,我已经删除了HTML实体字符(如&amp;ndash;&quot;),使代码更易阅读。如果您有任何其他问题,请随时告诉我。

英文:

I am creating a table and fetching data using Axios. However, I am not able to print the data &ndash; when I check, the data is being printed in the browser, but I am not able to print the particular data to a table format.

What should I change in my code?

import { useEffect, useState } from &quot;react&quot;;
import &quot;bootstrap/dist/css/bootstrap.min.css&quot;;
import { Table } from &quot;react-bootstrap&quot;;
import axios from &quot;axios&quot;;
export default function App() {
const [user, setUser] = useState([]);
useEffect(() =&gt; {
axios
.get(&quot;https://jsonplaceholder.typicode.com/users&quot;, (req, res) =&gt; {
res.json();
})
.then((data) =&gt; setUser({ ...user, data }))
.catch((error) =&gt; console.error(error));
});
return (
&lt;div className=&quot;App&quot;&gt;
&lt;h3 className=&quot;text-primary&quot;&gt;User List&lt;/h3&gt;
&lt;Table
variant=&quot;danger&quot;
striped
bordered
hover
className=&quot;shadow-lg text-center&quot;
&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;id&lt;/th&gt;
&lt;th&gt;Name&lt;/th&gt;
&lt;th&gt;UserName&lt;/th&gt;
&lt;th&gt;Email&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
{user?.data?.length &gt; 0 &amp;&amp;
user.data.map((user) =&gt; {
return (
&lt;tr key={user.id}&gt;
&lt;td&gt;{JSON.stringify(user.data[&quot;data&quot;].id)}&lt;/td&gt;
&lt;td&gt;{JSON.stringify(user.data[&quot;data&quot;].name)}&lt;/td&gt;
&lt;td&gt;{JSON.stringify(user.data[&quot;data&quot;].username)}&lt;/td&gt;
&lt;td&gt;{JSON.stringify(user.data[&quot;data&quot;].email)}&lt;/td&gt;
&lt;/tr&gt;
);
})}
&lt;/tbody&gt;
&lt;/Table&gt;
{/* &lt;div&gt;{JSON.stringify(user.data[&quot;data&quot;])}&lt;/div&gt; */}
&lt;/div&gt;
);
}

答案1

得分: 1

以下是代码的翻译部分:

import { useEffect, useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Table } from "react-bootstrap";
import axios from "axios";

export default function App() {
  const [user, setUser] = useState([]);

  useEffect(() => {
    axios
      .get("https://jsonplaceholder.typicode.com/users")
      .then((res) => {
        setUser(res.data);
      })
      .catch((error) => console.error(error));
  }, []);

  return (
    <div className="App">
      <h3 className="text-primary">User List</h3>
      <Table
        variant="danger"
        striped
        bordered
        hover
        className="shadow-lg text-center"
      >
        <thead>
          <tr>
            <th>id</th>
            <th>Name</th>
            <th>UserName</th>
            <th>Email</th>
          </tr>
        </thead>
        <tbody>
          {user?.length > 0 &&
            user.map((userData) => {
              return (
                <tr key={userData.id}>
                  <td>{userData.id}</td>
                  <td>{userData.name}</td>
                  <td>{userData.username}</td>
                  <td>{userData.email}</td>
                </tr>
              );
            })}
        </tbody>
      </Table>
      {/* <div>{JSON.stringify(user)}</div> */}
    </div>
  );
}

希望这对你有帮助。如果你有任何其他问题,不要犹豫提问。

英文:

for example

import { useEffect, useState } from &quot;react&quot;;
import &quot;bootstrap/dist/css/bootstrap.min.css&quot;;
import { Table } from &quot;react-bootstrap&quot;;
import axios from &quot;axios&quot;;
export default function App() {
const [user, setUser] = useState([]);
useEffect(() =&gt; {
axios
.get(&quot;https://jsonplaceholder.typicode.com/users&quot;)
.then((res) =&gt; {
setUser(res.data);
})
.catch((error) =&gt; console.error(error));
}, []);
return (
&lt;div className=&quot;App&quot;&gt;
&lt;h3 className=&quot;text-primary&quot;&gt;User List&lt;/h3&gt;
&lt;Table
variant=&quot;danger&quot;
striped
bordered
hover
className=&quot;shadow-lg text-center&quot;
&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;id&lt;/th&gt;
&lt;th&gt;Name&lt;/th&gt;
&lt;th&gt;UserName&lt;/th&gt;
&lt;th&gt;Email&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
{user?.length &gt; 0 &amp;&amp;
user.map((userData) =&gt; {
return (
&lt;tr key={userData.id}&gt;
&lt;td&gt;{userData.id}&lt;/td&gt;
&lt;td&gt;{userData.name}&lt;/td&gt;
&lt;td&gt;{userData.username}&lt;/td&gt;
&lt;td&gt;{userData.email}&lt;/td&gt;
&lt;/tr&gt;
);
})}
&lt;/tbody&gt;
&lt;/Table&gt;
{/* &lt;div&gt;{JSON.stringify(user)}&lt;/div&gt; */}
&lt;/div&gt;
);
}

答案2

得分: 1

替换useEffect代码如下:

useEffect(() => {
    axios
      .get("https://jsonplaceholder.typicode.com/users")
      .then((data) => setUser({ ...user, data }))
      .catch((error) => console.error(error));
  }, []);
英文:

Replace the useEffect code as follow.

useEffect(() =&gt; {
axios
.get(&quot;https://jsonplaceholder.typicode.com/users&quot;)
.then((data) =&gt; setUser({ ...user, data }))
.catch((error) =&gt; console.error(error));
}, []);

答案3

得分: 1

这是你要的翻译部分:

  1. You already know that calling this api will give you an array of users so you can initialise the state as empty array as:

    你已经知道调用此API将返回一个用户数组,因此你可以将状态初始化为空数组如下:

    const [users, setUsers] = useState([]);
    
  2. and when you are using axios then you don't have to use res.json(). axios will do it for you out of the box.

    当你使用axios时,你不需要使用res.json()axios会自动处理这个步骤。

  3. so, after getting data using get method of axios it will return you a promise and you can get data from its data property that is passed as the first argument. You can directly set state which will be an array of objects.

    因此,在使用axiosget方法获取数据后,它将返回一个Promise,你可以从它的data属性中获取数据,该属性作为第一个参数传递。你可以直接设置状态,这将是一个对象数组。

  4. Here I've destructured the object to get only the data property.

    在这里,我已解构对象,仅获取了data属性。

  5. Since users will be an array of objects, so you don't have to do any check. You can directly use user.id to get the respective property.

    由于users将是一个对象数组,所以你不需要进行任何检查。你可以直接使用user.id来获取相应的属性。

  6. Codesandbox link

    Codesandbox链接

export default function App() {
  const [users, setUsers] = useState();

  useEffect(() => {
    axios
      .get("https://jsonplaceholder.typicode.com/users")
      .then(({ data }) => setUsers(data))
      .catch((error) => console.error(error));
  }, []);

  return (
    <div className="App">
      <h3 className="text-primary">User List</h3>
      <Table variant="danger" striped bordered hover className="shadow-lg text-center">
        <thead>
          <tr>
            <th>id</th>
            <th>Name</th>
            <th>UserName</th>
            <th>Email</th>
          </tr>
        </thead>
        <tbody>
          {users.map((user) => {
            return (
              <tr key={user.id}>
                <td>{user.id}</td>
                <td>{user.name}</td>
                <td>{user.username}</td>
                <td>{user.email}</td>
              </tr>
            );
          })}
        </tbody>
      </Table>
    </div>
  );
}

如果还有其他问题或需要更多帮助,请告诉我。
<details>
<summary>英文:</summary>
You already know that calling this api will give you an array of users so you can initialise the state as empty array as:
const [users, setUsers] = useState([]);
and when you are using `axios` then you don&#39;t have to use `res.json()`. `axios` will do it for you out of the box.
axios
.get(&quot;https://jsonplaceholder.typicode.com/users&quot;)
.then(({ data }) =&gt; setUsers(data))
.catch((error) =&gt; console.error(error));
so, after getting data using `get` method of `axios` it will return you a promise and you can get data from its `data` property that is passed an first args. You can directly set state which will be an array of objects.
.then(({ data }) =&gt; setUsers(data))
Here I&#39;ve destructed the object to get only the `data` property.
----------
Since `users` will be an array of objects, so you don&#39;t have to do any check. You can directly use `user.id` to get the respective property.
[`Codesandbox link`][1]
export default function App() {
const [users, setUsers] = useState([]);
useEffect(() =&gt; {
axios
.get(&quot;https://jsonplaceholder.typicode.com/users&quot;)
.then(({ data }) =&gt; setUsers(data))
.catch((error) =&gt; console.error(error));
}, []);
return (
&lt;div className=&quot;App&quot;&gt;
&lt;h3 className=&quot;text-primary&quot;&gt;User List&lt;/h3&gt;
&lt;Table
variant=&quot;danger&quot;
striped
bordered
hover
className=&quot;shadow-lg text-center&quot;
&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;id&lt;/th&gt;
&lt;th&gt;Name&lt;/th&gt;
&lt;th&gt;UserName&lt;/th&gt;
&lt;th&gt;Email&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
{users.map((user) =&gt; {
return (
&lt;tr key={user.id}&gt;
&lt;td&gt;{user.id}&lt;/td&gt;
&lt;td&gt;{user.name}&lt;/td&gt;
&lt;td&gt;{user.username}&lt;/td&gt;
&lt;td&gt;{user.email}&lt;/td&gt;
&lt;/tr&gt;
);
})}
&lt;/tbody&gt;
&lt;/Table&gt;
{/* &lt;div&gt;{JSON.stringify(user.data[&quot;data&quot;])}&lt;/div&gt; */}
&lt;/div&gt;
);
}
[1]: https://codesandbox.io/s/nameless-architecture-7drz37?file=/src/App.js
</details>

huangapple
  • 本文由 发表于 2023年2月18日 12:37:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75491226.html
匿名

发表评论

匿名网友

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

确定