![](/img/trans.png)
[英]React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array. props in useEffect have no data
[英]React Hook useEffect has a missing dependency: 'props.myObj'. Either include it or remove the dependency array
下面的代碼工作正常。 每次props.myObj["test"]?.prop1?.data
改變它都會觸發useEffect
的函數。 但是,我收到警告React Hook useEffect has a missing dependency: 'props.myObj'. Either include it or remove the dependency array
React Hook useEffect has a missing dependency: 'props.myObj'. Either include it or remove the dependency array
我不能將它包含在依賴項數組中,因為它會導致無限循環(因為props.myObj
具有不斷變化的嵌套對象)。 當然,我無法刪除當前的依賴項。 那么知道如何解決這個問題嗎?
useEffect(() => {
const data = props.myObj["test"]?.prop1?.data || {};
if (data["first"]) {
setTotalData(data["first"].data.length);
}
}, [props.myObj["test"]?.prop1?.data]);
如果"test"
是一個常量,則改為執行以下操作。
const data = props.myObj.test?.prop1?.data || {};
如果不是,那么您使用useEffect
鈎子是錯誤的,因為依賴項列表中的變量在引用方面應該是常量。
您需要比較最后一個(前一個) totalData
,如果前一個totalData
(即數據["first"].data.length
)與 new 不同,則只執行setTotalData
。 否則,如果每次都改變,那么你將有無限循環。 但是看起來您正在根據道具計算一些值。 這可以作為計算值使用useMemo
。
const totalData = React.useMemo(props.myObj?.test?.prop1?.data?.first ? data?.first?.data?.length : 0,[props.myObj])
您應該禁用警告:
useEffect(() => {
...
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
這樣做仍然是一個很好的做法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.