我有此反应设置,我定义了一个称为ApiTable
的钩子,并具有renderTable
方法。我要做的是从API端点获取数据,https://jsonplaceholder.typicode.com/users
并将其返回具有适当类别的表格。
现在,它正在将所有列划过左侧,如下所示。当前,数据尚未显示,并将其压实到左侧。我很确定我的表数据设置错误。
另外,我不确定Axios请求是否应该在使用效果内部。
https://imgur.com/a/Up4a56v
const ApiTable = () => {
const url = 'https://jsonplaceholder.typicode.com/users';
const [data, setData] = useState([]);
useEffect(() => {
setData([data]);
axios.get(url)
.then(json => console.log(json))
}, []);
const renderTable = () => {
return data.map((user) => {
const { name, email, address, company } = user;
return (
<div>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Address</th>
<th>Company</th>
</tr>
</thead>
<tbody>
<tr>
<td>name</td>
<td>email</td>
<td>address</td>
<td>company</td>
</tr>
</tbody>
</div>
)
})
}
return (
<div>
<h1 id='title'>API Table</h1>
<Table id='users'>
{renderTable()}
</Table>
</div>
)
};
您正在正确获取数据,但将数据设置为错误。
还要迭代data
数组时,每次都在打印table head
,而data
数组address
和company
是对象,因此您无法指向对象。
您需要这样做,
const App = () => {
const url = 'https://jsonplaceholder.typicode.com/users'
const [data, setData] = useState([])
useEffect(() => {
axios.get(url).then(json => setData(json.data))
}, [])
const renderTable = () => {
return data.map(user => {
return (
<tr>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.address.street}</td> //only street name shown, if you need to show complete address then you need to iterate over `user.address` object
<td>{user.company.name}</td> //only company name shown, if you need to show complete company name then you need to iterate over `user.name` object
</tr>
)
})
}
return (
<div>
<h1 id="title">API Table</h1>
<table id="users"> //Your Table in post changed to table to make it work
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Address</th>
<th>Company</th>
</tr>
</thead>
<tbody>{renderTable()}</tbody>
</table>
</div>
)
}
demo