【发布时间】:2019-11-17 11:00:46
【问题描述】:
我正在尝试使用 React 钩子来重建一些作为功能组件的类组件来进行获取。
我可以获取数据,这很好,但它每隔几毫秒调用一次我的 API,我只希望它获取数据并停止,就像它在具有 componentDidMount 的类组件中一样。
我想我可以明白它为什么会这样做(函数内部的 fetchData() 意味着它会继续调用自己)但我不知道如何解决它。
我尝试添加一个 setInterval,更改顺序,并将 fetchData() 移到函数外部(组件不会呈现,因为它当时未定义)。
const MyFunction = () => {
const [apiResponse,setApiResponse] = useState({})
async function fetchData() {
const res = await fetch(`http://localhost:9000/example`,{
method: 'POST',
mode: 'cors',
body: JSON.stringify({date: '20190707'}),
headers: {'content-type': 'application/json',
credentials: 'include'
}
})
res
.json()
.then(res => setApiResponse(res))
}
useEffect(() => {
fetchData();
});
var queryResult = apiResponse['units']
return (
<React.Fragment>
<CardHeader color={"info"} stats icon>
<CardIcon color={"info"}>
<Icon>{"trending_up"}</Icon>
</CardIcon>
<p className={''}>Drop In</p>
<h3 className={''}>
{queryResult} <small>Units</small>
</h3>
</CardHeader>
<CardFooter ></CardFooter>
</React.Fragment>
);
}
【问题讨论】:
-
您需要告诉 useEffect 它的依赖项是什么,参见例如stackoverflow.com/questions/53070970/infinite-loop-in-useeffect。这也包含在文档中:reactjs.org/docs/hooks-effect.html.
标签: reactjs react-hooks