检查数据库信息是否拉取时如何停止"top many rerenders"?



嗨,我试图在提取数据库数据和进行BMI计算之间造成延迟,但if语句检查导致了"重复次数过多"的问题。我该怎么绕过这个?

function Main_page(props) {
const [loading, setLoading] = useState(true)
const [healthData, healthDataSet] = useState(null)
const [BMI, BMIset] = useState(null)
const [BMR, BMRset] = useState(null) 

useEffect(() => {
const user = Authentication.auth().currentUser;
{
user !== null &&
Authentication.firestore().collection('Health_data')
.doc(user.uid)
.get()
.then(doc => {
healthDataSet(doc.data())
setLoading(false)
}).catch(function (error) {
console.error("Error reading health", error);
});
}
return () => {
document.body.style.overflow = 'unset';
}
}, []);
if (!loading) {
BMIset(healthData.weight/(healthData.height^2))
}

这是我的代码片段,只有在加载设置为false时才应该进行计算。这里有什么解决办法?提前谢谢。

useEffect+它的第二个参数就可以了。

useEffect(() => {
if(!loading && healthData !== null) 
BMIset(healthData.weight/(healthData.height^2))
}, [loading, healthData]);

这样:

  • loading的默认状态为true
  • healthData的默认状态为null

您查询firestore,当它返回成功响应时,您设置:

  • loadingfalse
  • healthData至消防仓库返回的文件

如果不更改loadinghealthData,则新的useEffect将跳过效果。然后当loadingfalse&healthData不为空。

最新更新