英文:
Empty object response on fetching data from a local JSON server in React
问题
我试图显示来自本地JSON服务器的数据,但遇到了错误。
我知道fetch返回一个异步的promise,并且需要几毫秒才能成功获取数据,但我的问题是,我如何避免或忽略第一个空对象响应,只在数据成功获取后执行map,因为我得到了“Cannot read properties of undefined (reading 'map')”错误。
英文:
I`m trying to display the data from a local JSON server but I get into errors.
I know that fetch returns a promise which is asynchronous and it takes couple of milliseconds to succesfully fetch the data but my question is, how can I avoid or ignore the first empty object response and only execute the map on the data when it`s fetched because I get "Cannot read properties of undefined (reading "map)"
function App() {
const [data, setData] = useState({});
const [loaded, setLoaded] = useState(false);
useEffect(() => {
fetch("http://localhost:8000/data")
.then((response) => {
if (!response.ok) {
throw new Error("Data failed to fetch");
}
return response.json();
})
.then((data) => {
setData(data);
setLoaded(true);
});
}, []);
return (
<div className="App">
<Card data={data} loaded={loaded} />
</div>
);
}
const Card = ({ data, loaded }) => {
return (
<div>
{data.activeUsers.user432.map((user) => (
<h1 key={user.id}>{user.id}</h1>
))}
</div>
);
};
答案1
得分: 0
尝试这个 -
{ data.activeUsers?.user432.map((user) => (
<h1 key={user.id}>{user.id}</h1>
))}
英文:
try this -
{ data.activeUsers?.user432.map((user) => (
<h1 key={user.id}>{user.id}</h1>
))}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论