可能每个网站都会以这样或那样的方式消耗数据。最常见的情况是,你会遇到需要在表中显示数据的情况。
在本教程中,我们将研究如何获取JSON数据并将其显示在一个表中。
让我们开始吧!
项目设置
通过在你的机器上创建react app或打开浏览器并访问react.new来开始。
一个新的CodeSandbox环境将打开,并设置了React项目。
从API获取数据
在React中,有很多方法来获取数据,但在本教程中,我们将使用**fetch()**函数来获取假的JSON数据。
我们将使用一个假的JSON APIdummyjson.com/products,它返回随机产品的数据,然后我们将使用这些数据在我们的表中显示:
// App.js
import { useEffect } from "react";
import "./App.css";
function App() {
useEffect(() => {
fetch(`https://dummyjson.com/products`)
.then((response) => response.json())
.then((actualData) => console.log(actualData))
.catch((err) => {
console.log(err.message);
});
}, []);
return (
<div>
<p>Hello, world!</p>
</div>
);
}
export default App;
在这段代码中,我们在useEffect钩子中获取数据,这样它就只在初始渲染时加载数据。你可以在这里了解更多关于如何在React中获取数据。
运行React应用程序,你会在浏览器的控制台中看到数据:
接下来,我们将看到如何在一个表中显示这些数据。
在React中创建一个表
在JSX里面创建一个普通的HTML表格。我们也可以使用react-table库,它有一堆可用的功能,但为了本教程的目的,我们将使用普通的表格。
// App.js
import { useEffect, useState } from "react";
import "./App.css";
function App() {
useEffect(() => {
fetch(`https://dummyjson.com/products`)
.then((response) => response.json())
.then((actualData) => {
console.log(actualData);
})
.catch((err) => {
console.log(err.message);
});
}, []);
return (
<div>
<tbody>
<tr>
<th>Name</th>
<th>Brand</th>
<th>Image</th>
<th>Price</th>
<th>Rating</th>
</tr>
</tbody>
</div>
);
}
export default App;
现在,我们将利用**useState**钩子来存储我们获取的所有数据。钩子中的 数据变量是一个空数组,由 setData函数进一步更新。
// App.js
import { useEffect, useState } from "react";
import "./App.css";
function App() {
const [data, setData] = useState([]);
const fetchData = () => {
fetch(`https://dummyjson.com/products`)
.then((response) => response.json())
.then((actualData) => {
console.log(actualData);
setData(actualData.products);
console.log(data);
})
.catch((err) => {
console.log(err.message);
});
};
useEffect(() => {
fetchData();
}, []);
return (
<div>
<tbody>
<tr>
<th>Name</th>
<th>Brand</th>
<th>Image</th>
<th>Price</th>
<th>Rating</th>
</tr>
{data.map((item, index) => (
<tr>
<td>{item.title}</td>
<td>{item.brand}</td>
<td>
<img src="{item.thumbnail}" alt="" height="{100}" />
</td>
<td>{item.price}</td>
<td>{item.rating}</td>
</tr>
))}
</tbody>
</div>
);
}
export default App;
在这段代码中,我们正在映射数据数组,其中包含我们获取的所有数据,并将其显示在表格中。现在运行React应用程序并打开你的浏览器。
这里是最终的结果。
结果
结论
在表格中显示JSON数据并不是一项困难的任务,但许多开发者都在努力寻找完美的方法来实现它。在本教程中,我们研究了如何从API中获取JSON数据并在表中显示。现在,请继续努力,让它变得漂亮。
非常感谢您阅读本教程。
如果你有任何问题或建议,请随时评论。如果你想就某一特定主题索取任何文章,请通过 "**关于 "**页面联系我们。我们很愿意听到你的意见。