在我的应用程序中,当matches被更改时,我想刷新。但是,如果我将matches放在useEffect依赖数组中,页面似乎就会不断地重新加载。
密码,
const [matches, setMatches] = useState();
const loadData = async() => {
setPendingApiCall(true);
await apiCalls
.getMatches(id)
.then((response) => {
setPendingApiCall(false)
setMatches(response.data)
})
.catch((error) => {
setPendingApiCall(false)
setMatchError('Error loading matches');
console.log(error)
})
}
useEffect(() => {
loadData();
}, [matches])基本上,当页面加载时,它调用我的api并获取匹配的详细信息,并将matches变量设置为显示在页面上的数据。比赛数据包含分数,当用户更新比赛分数时,我调用loadData函数,它将返回matches的新数据。
根据我对react的有限理解,将matches放在依赖数组中,如果matches更改,应该会导致页面数据刷新。
但是如果我将匹配放在依赖数组中,页面就会不断地调用api。(我有一个按钮,当挂起的api调用正在进行时,该按钮会被禁用,并且该按钮一直在活动和禁用之间闪烁)
我已经读过一些文档和一些这样的帖子,但是我看不出我做错了什么。
发布于 2022-04-27 20:57:03
试试这个:
const [matches, setMatches] = useState();
const loadData = async() => {
setPendingApiCall(true);
await apiCalls
.getMatches(id)
.then((response) => {
setPendingApiCall(false)
setMatches(response.data)
})
.catch((error) => {
setPendingApiCall(false)
setMatchError('Error loading matches');
console.log(error)
})
}
useEffect(() => {
loadData();
}, [])
https://stackoverflow.com/questions/72035157
复制相似问题