[英]Print json from api in React
我有一个 php api 选择数据库并在 json 中返回此数据,我想在 React App 的表格中显示它们。 我试过这种方式但没有结果:
import React from 'react'
import JsonData from 'http://localhost/index.php' //My test api is index.php
function Body(){
const DisplayData=JsonData.map(
(info)=>{
return(
<tr>
<td>{info.id}</td>
<td>{info.name}</td>
</tr>
)
}
)
return(
<div>
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Nome</th>
</tr>
</thead>
<tbody>
{DisplayData}
</tbody>
</table>
</div>
)
}
export default Body;
您不能在反应中以这种方式进行 API 调用。
要进行 API 调用,您可以使用fetch
function,或依赖外部库,例如axios 。
获取示例:
componentDidMount() {
// Simple GET request using fetch
fetch('http://localhost/index.php')
.then(response => response.json())
.then(data => this.setState({ myCoolJSON: data}));
}
请记住,调用是异步进行的。
你的代码有一些问题,
首先,您应该使用 http 客户端来获取您的数据,例如fetch
、 axios
等
其次,您应该使用state
来管理您的数据,因为您应该在获取数据后重新渲染您的组件,或者您可以重新考虑您的组件组合,以便您的组件只有在数据准备好后才安装在页面中(并且将准备好的数据作为道具传递)。
这是使用您的代码的工作示例:
https://codesandbox.io/s/fervent-chaum-uxwexq?file=/src/App.js
这是请求 function
async function fetchData() {
const url = "https://dummyjson.com/carts";
const r = await (await fetch(url)).json();
return r.carts[0].products;
}
这定义了 state 并在组件安装后进行调用:
const [rows, setRows] = React.useState([]);
async function fetchRows() {
setRows(await fetchData());
}
React.useEffect(() => fetchRows, []);
使用.map()
渲染列表时,还可以考虑使用key
属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.