我正在學習 ReactJS 中的表格,但無法在列中呈現獲取的資料。實際上,API 被獲取(在控制臺中)但不會將其物件呈現為 Material UI 表中的列。
使用的 API = api.twelvedata.com/cryptocurrencies,方法 = Get,Axios
我想以以下表格格式將 API 中的所有符號和貨幣報價呈現到表格中:

請幫助,如果可能,請解釋錯誤。
import React from 'react'
import { useState, useEffect } from 'react'
import axios from 'axios'
import Table from '@mui/material/Table';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
export default function BasicTable() {
const [data,setData] = useState([])
const columns = [
{field: 'symbol'},
{field: 'currency_quote'},
]
useEffect(()=>{
axios.get(`https://api.twelvedata.com/cryptocurrencies`)
.then(
(a)=>{
console.log(a.data)
setData(a.data.symbol)
}
)
.catch(
(b)=>{
console.log(Error)
}
)
},[])
return (
<TableContainer component={Paper}>
<Table sx={{ minWidth: 650 }} aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>Stock Name</TableCell>
<TableCell>Quote</TableCell>
</TableRow>
</TableHead>
{data && columns.map(data=><div>{data.field}</div>)}
</Table>
</TableContainer>
);
}
uj5u.com熱心網友回復:
好吧,看起來您正在保存未定義的資料。回應資料是一個data具有陣列屬性的物件。IE response.data.data,或者a.data.data在你的情況下。
// 20211111011738
// https://api.twelvedata.com/cryptocurrencies
{
"data": [
{
"symbol": "0xBTC/BTC",
"available_exchanges": [
"Hotbit",
"Mercatox"
],
"currency_base": "0xBitcoin",
"currency_quote": "Bitcoin"
},
{
"symbol": "0xBTC/ETH",
"available_exchanges": [
"Hotbit",
"Mercatox"
],
"currency_base": "0xBitcoin",
"currency_quote": "Ethereum"
},
...
因此a.data.symbol在嘗試更新狀態時未定義。
setData(a.data.symbol) // <-- undefined!
要解決您只想將回應data陣列屬性保存到狀態。我還建議使用比aGET 請求的回應值更有意義的識別符號。
useEffect(() => {
axios.get(`https://api.twelvedata.com/cryptocurrencies`)
.then(response => {
setData(response.data.data)
})
.catch(console.error);
}, []);
下一個問題是映射。您有 2 列,符號和貨幣報價,因此這些是您要映射到表格主體的表格行(而不是 divs)中的屬性。
<TableContainer component={Paper}>
<Table sx={{ minWidth: 650 }} aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>Stock Name</TableCell>
<TableCell>Quote</TableCell>
</TableRow>
</TableHead>
<TableBody> // <-- table body
{data.map(({ currency_quote, symbol }, index) => (
<TableRow key={index}> // <-- table row with React key(!!)
<TableCell>{symbol}</TableCell>
<TableCell>{currency_quote}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/359679.html
