【发布时间】:2020-08-27 05:22:33
【问题描述】:
我在 react 钩子和效果方面有点新,我在使用 useEffect 时遇到了麻烦
useEffect( _ => {
(async _ => {
const res = await axios.get('/api/laf/getreportlostitem');
getReports(res.data);
setLoading(false);
})();},[reports]);
上面的代码是我构建的一个useEffect,用来使用axios获取数据库中的所有数据,我把所有的数据都放在了一个叫做reports的状态中。
// Data State for getting the reports
const [reports, getReports] = useState([]);
但是当我 console.log 报告时,它会导致无限循环。不知道为什么?
让我向您展示我所做的简短操作。
我正在做一个按钮,当它被点击时,它的 id 报告的状态将被更新。
<Button onClick={ _ => setAsFound(row.id)} variant="contained" color="primary">Set as found</Button>
|
<ClaimedButton onClick={ _ => setAsClaimed(row.id)} variant="contained" color="primary">
Set as claimed
</ClaimedButton>
这是该州报告结构的示例草稿。
{ name, src, yr, campus, department, course, details, contact, status }
如您所见,对象中有一个“状态”数据。因此,当我单击其中一个按钮时,报告状态中的数据将被更新。这是按钮的onclick功能。
const setAsFound = id => {
if(window.confirm("Are you sure this report item is now found?") ){
const updateStatusFound = {
status: foundData
};
props.setReportToFound(id, updateStatusFound);
}
};
const setAsClaimed = id => {
if(window.confirm("Are you sure this report item is now claimed?")){
const updateStatusClaimed = {
status: claimedData
};
props.setReportToClaimed(id, updateStatusClaimed);
}
};
founData 和claimData 的值是这个。
const [foundData, setFoundData] = useState('Found, Not Claimed');
const [claimedData, setClaimedData] = useState('Found and Claimed');
这只是操作完成后将在数据库中发送的状态值。
其他代码只是我正在处理的操作和功能。但我主要关心的是为什么即使是刚刚在组件中呈现的数据,报告状态也会导致无限循环?我什至有一个依赖项,因此当数据更新时,报告状态将被更新并重新呈现数据。我试过不将报告作为依赖项包括在内。但问题是当我删除它时,数据不会更新。有什么想法可以停止无限循环吗?
【问题讨论】:
标签: reactjs