簡體   English   中英

如何使用React自定義鈎子重用api中的數據獲取邏輯

[英]How to reuse data fetching logic from api using react custom hooks

我有兩個基於用戶類型呈現不同UI的組件。 這兩個組件都具有將近50%從api讀取數據,連接到存儲的相似邏輯。

我嘗試過,通過創建自定義鈎子來重用登錄名。

const { products, loading} = useFetchProducts(userId);

現在我可以定義一個useFetchProducts減速器

  const useFetchProducts= (userId) => {
   const [ loading, setLoading ] = useState(false);
   const [ products, setProducts ] = useState(null);

   useEffect(() => {
       setLoading(true);
         fetchUserProducts(userId).then((res) => {
           setLoading(false);
           setProducts(res.data);  
     }); 
   }, [])
 }

我如何從該減速器中退回產品並將狀態加載到我的組件中,以隱藏或顯示加載器以及顯示產品列表,

您只需要從自定義鈎子返回值。

const useFetchProducts= (userId) => {
   const [ loading, setLoading ] = useState(false);
   const [ products, setProducts ] = useState(null);

   useEffect(() => {
       setLoading(true);
         fetchUserProducts(userId).then((res) => {
           setLoading(false);
           setProducts(res.data);  
     }); 
   }, [])
   return {loading, products}
 }

之所以會這樣工作,是因為當數據可用時,它將導致重新渲染,因此,使用自定義鈎子的組件將重新渲染,從而導致更新

您需要從自定義鈎子返回值。

const useFetchProducts= (userId) => {
   const [ loading, setLoading ] = useState(false);
   const [ products, setProducts ] = useState(false);

   useEffect(() => {
       setLoading(true);
         fetchUserProducts(userId).then((res) => {
           setLoading(false);
           setProducts(res.data);  
     }); 
   }, [])
   return { products, loading }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM