我通常对React.js来说是超级新手,想在这里使用此api:https://covidtracking.com/api/v1/states/current.json创建包含来自美国各州的最新COVID-19数据的表。问题是,当我渲染应用程序时,我似乎无法将数据上传到表中。任何帮助,将不胜感激,谢谢。
import React, { useMemo, useState, useEffect } from "react";
import axios from "axios";
import Table from "./Table";
import "./App.css";
function App() {
const columns = useMemo (
()=> [
{
Header: "State",
accessor: "show.state"
},
{
Header: "Positive Cases",
accessor: "show.positive"
},
{
Header: "Recovered Cases",
accessor: "show.recovered"
}
]
)
const [data, setData] = useState([]);
useEffect(() => {
(async () => {
const result = await axios("https://covidtracking.com/api/v1/states/current.json");
setData(result.data);
})();
}, []);
return (
<div className="App">
<Table columns = {columns} data = {data} />
</div>
);
}
export default App;
我正在使用此个人项目的指南来掌握React Table的功能:https://blog.logrocket.com/complete-guide-building-smart-data-table-react/
我的表格文件:
import React from "react";
import { useTable } from "react-table";
export default function Table({ columns, data }) {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow
} = useTable({
columns,
data
});
return (
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render("Header")}</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map((row, i) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
})}
</tr>
);
})}
</tbody>
</table>
);
}
import React, { useMemo, useState, useEffect } from "react";
import axios from "axios";
import Table from "./Table";
import "./App.css";
function App() {
// here you set a state to tell the component it need to wait
// until the result is fetched from the api
const [loadingData, setLoadingData] = useState(true);
const columns = useMemo(() => [
{
Header: "State",
accessor: "show.state",
},
{
Header: "Positive Cases",
accessor: "show.positive",
},
{
Header: "Recovered Cases",
accessor: "show.recovered",
},
]);
const [data, setData] = useState([]);
useEffect(() => {
async function getData() {
await axios
.get("https://covidtracking.com/api/v1/states/current.json")
.then((response) => {
// check if the data is populated
console.log(response.data);
setData(response.data);
// you tell it that you had the result
setLoadingData(false);
});
}
if (loadingData) {
// if the result is not ready so you make the axios call
getData();
}
}, []);
return (
<div className="App">
{/* here you check if the state is loading otherwise if you wioll not call that you will get a blank page because the data is an empty array at the moment of mounting */}
{loadingData ? (
<p>Loading Please wait...</p>
) : (
<Table columns={columns} data={data} />
)}
</div>
);
}
export default App;