javascript - axios方法Get:我的表无法显示数据
问题描述
我想在我的网站上显示一个 JSON。我正在使用一个带有安全令牌的 API,一切都很好,直到我想在我的页面中显示 json 的数据,并且它只存在于我的控制台中,因为我可以在我的控制台中看到数据。我希望你能帮助我。
import React from 'react';
import axios from 'axios';
const Table = () => {
const url = 'someApi';
const token = 'someToken'
axios(url, {
method: 'get',
headers: {
'Authorization': `Bearer ${token}`
},
'body': JSON.stringify({
name: this.state.name,
quantity: this.state.quantity,
price: this.state.price,
})
})
// .then(response => response.json())
.then(response => {
console.log(response);
})
.catch(error => console.error(error));
return(
<>
<table>
<thead>
<tr>
<th>sku</th>
<th>name</th>
<th>quantity</th>
<th>price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</>
)
}
export default Table;
解决方案
我认为你应该更多地了解反应以及如何使用地图功能,我更喜欢在 youtube 上观看一些关于它的 tuts。
生病分享一些axios和映射数据的简单用法,希望对你有所帮助。
const Table = () => {
const [data, setData] = React.useState(null);
React.useEffect(() => {
if (!data) {
axios("https://jsonplaceholder.typicode.com/users", {
method: "GET",
})
.then((res) => setData(res.data))
.catch((error) => console.error(error));
}
},[data]);
return (
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>email</th>
<th>phone</th>
</tr>
</thead>
<tbody>
{data
? data.map((d) => (
<tr key={d.id}>
<td>{d.id}</td>
<td>{d.name}</td>
<td>{d.email}</td>
<td>{d.phone}</td>
</tr>
))
: null}
</tbody>
</table>
);
}
ReactDOM.render(
<Table />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<div id="react"></div>
推荐阅读
- css - 引导网格:如何更改列的位置?
- java - 从 Oracle Java 8 更新到采用 OpenJDK
- continuous-integration - 我正在寻找 xml 和 Python 的代码策略执行工具
- javascript - 如何在 sagas 中使用异步加载的资产与本机反应?
- python - 处理来自 .json 文件的密钥中的密钥
- rust - &dyn Trait 和 Box 有什么区别
动态调度? - apache-kafka - @KafkaListener vs ConsumerFactory groupId
- mysql - Xampp MySQL 意外关闭插件'FEEDBACK'被禁用
- angular - 无法在 Angular 组件中使用 ngFor 获取数据
- ios - 从 React Native App Clip 中的 NSUserActivity 访问网页 URL