[英]How to execute React custom hook only when data is available or Apollo client loading is false
我有自定義 React 掛鈎,它添加了一些腳本並向 window object 添加了一個變量:
const useMyHook = ({ id, type }: Props) => {
useScript('https:domain/main.js');
useScript('https://domain/main2.js');
useEffect(() => {
window.mydata = { id: `${id}`, type: `${type}` };
}, [id]);
};
我正在使用Apollo 客戶端和 GraphQl 來獲取數據。
在我的 Page 組件中,當我使用console.log(myData)
時,數據返回未定義,然后在它返回數據之后立即返回(不刷新)。 我正在使用片段。
從useQuery掛鈎我可以獲得loading
變量。 我如何必須使用loading
和我的自定義掛鈎所以當加載 === false -> 使用我的自定義掛鈎。
我試過這樣的事情:
const foo = useMyHook({ id: myData.id, type: myData.type });
然后在下面的組件中返回:
return (
{!loading && foo}
// Rest of the component jsx code
)
但有時它仍然首先返回未定義?
我該如何解決這個問題?
# 更新:
現在我添加了另一個道具loading: boolean
並將其添加到自定義掛鈎中:
useEffect(() => {
if (!loading) {
window.mydata = { id: `${id}`, type: `${type}` };
}
}, [id]);
這是正確的做法嗎。 為什么我的片段查詢首先返回undefined
?
您可以添加另一個類似 enabled 的道具來處理這個問題
像這樣:
使用MyHook.tsx:
const useMyHook = ({ id, type,enabled }: Props) => {
useScript('https:domain/main.js');
useScript('https://domain/main2.js');
useEffect(() => {
if(enabled)
{
window.mydata = { id: `${id}`, type: `${type}` };
}
}, [enabled]);
};
其他組件:
const foo = useMyHook({ id: myData.id, type: myData.type,enabled:!loading && (data || error) });
return foo
並且您需要使用可以從 useQuery 中解構的數據和錯誤(例如 loading )來確保加載是否為假並且存在數據或錯誤(這是因為組件第一次呈現時,加載為假但是數據和錯誤不存在,因為請求尚未提交,這就是為什么你首先看到 undefined )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.