reactjs - 使用反应 useEffect 钩子
问题描述
我正在使用 React useEffect 挂钩来获取数据并显示加载指示器,但我的加载不起作用。
下面是 useEffect Hook 代码:
useEffect(() => {
fetchEvents();
}, []);
fetchEvents
功能代码:
const fetchEvents = () => {
setLoading(true);
const requestBody = {
query: `
query {
events {
_id
title
description
price
date
creator {
_id
email
}
}
}
`
};
fetch("http://localhost:5000/graphql", {
headers: {
"Content-Type": "application/json"
},
method: "POST",
body: JSON.stringify(requestBody)
})
.then(res => {
if (res.status !== 200 && res.status !== 201) {
throw new Error("Failed");
}
return res.json();
})
.then(resData => {
const events = resData.data.events;
setEvents(events);
setLoading(false);
})
.catch(err => {
console.log(err);
setLoading(false);
});
};
解决方案
您应该提供更多信息,但这里有一个示例:
import React, { useState, useEffect } from 'react';
import { Spinner } from 'react-bootstrap';
const MyComponent = () => {
const [isLoading, setIsLoading] = useState(false);
const [data, setData] = useState([]);
useEffect(() => {
setIsLoading(true);
fetch('/data/endpoint')
.then((res) => res.json)
.then((response) => {
setData([...response]);
setIsLoading(false);
});
}, []);
return isLoading ? (
<Spinner />
) : (
<ol>
data.map(items => <li>{items.label}</li>);
</ol>
);
};
推荐阅读
- java - Java Process Builder 总是在错误流中提供数据
- python - Python 函数 if else
- tableau-api - 在 Tableau 中,如何创建基于跨行数据对数据进行分类的计算字段?
- c# - 使用外键在sql中插入一个值
- kubernetes - 如何从 Kubernetes ConfigMap 中执行 shell 命令?
- c# - 在 C# 中插值基数曲线
- python - Python 3.6.4 不和谐机器人。嵌入图像
- lua - 检查元表是否为只读
- postgresql - 如何从我的表 Postgres 中选择 json
- google-maps - 谷歌地图 SDK iOS 地面覆盖在地图上显示几张图像和奇怪的黑色覆盖后停止加载。之后应用程序崩溃