我正在使用react hooks
从API中获取数据,并且希望将其显示在表格中。看似非常简单,但是我缺少了一些东西。 问题是<table>
中没有呈现数据。
另外,我想知道我是否在正确的方向上走得太远。如果我朝最佳实践的方向走错了,请纠正我。
../ app.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import Header from './components/Header';
import UserList from './components/UserList';
export default function App() {
return (
<BrowserRouter>
<Header />
<Switch>
<Route exact path='/' component={UserList} />
</Switch>
{/* <Sidebar /> */}
</BrowserRouter>
);
}
ReactDOM.render(<App />, document.getElementById('app'));
./ helpers / FetchData / FetchData.js
import React from 'react';
export const useFetch = (url, options) => {
const [response, setResponse] = React.useState({});
const [error, setError] = React.useState({});
React.useEffect(() => {
const fetchData = async () => {
try {
const res = await fetch(url, options);
const json = await res.json();
setResponse(json);
} catch (error) {
setError(error);
}
};
fetchData();
}, []);
return { response, error };
};
../ components / UserList / UserList.js
import React from 'react'
import { useFetch } from '../../helpers/FetchData';
export default function UserList() {
const res = useFetch('https://randomuser.me/api', {});
if(!res.response.results) {
return <div>Loading...</div>
}
const data = res.response.results;
console.log(data);
return (
<table className="table table-striped table-dark">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">City</th>
<th scope="col">State</th>
</tr>
</thead>
<tbody>
{data && data.map(row => {
<tr>
<th scope="row" key={row.id}>{row.id}</th>
<td>{row.name.first}}</td>
<td>{row.name.last}</td>
<td>{row.location.city}</td>
<td>{row.location.state}</td>
</tr>
})}
</tbody>
</table>
)
}
编辑:
这是UserList组件中console.log(data)
语句的结果,所以我知道有数据正在返回:
之所以没有看到任何表行,是因为您的data.map
调用未返回任何内容。您定义它的方式需要包括一个return
调用,如下所示:
{data && data.map(row => {
return (
<tr>
<th scope="row" key={row.id}>{row.id}</th>
<td>{row.name.first}}</td>
<td>{row.name.last}</td>
<td>{row.location.city}</td>
<td>{row.location.state}</td>
</tr>
);
})}
根据您代码中当前的定义,它在map函数中创建tr
,但不返回它。
列出您的依赖项,我为您提供了一个有效的示例。我还给人的印象是,您不应该使用具有使用效果的异步功能来使用.then。
export const useGetMessageData = (url) => {
const [messageData, setMessageData] = useState({ user: null, loading: true });
useEffect(() => {
setMessageData(messageData => ({ messages: messageData.data, loading: true }));
fetch(url)
.then(response => response.json())
.then(data => {
setMessageData({ messageData: data, loading: false });
});
}, [url, setMessageData]);
return messageData;
};
问题是您的map
实际上没有返回任何内容。代替
data.map(row => {
// React elements
});
切换方括号
data.map(row => (
// react elements
))