簡體   English   中英

反應鈎子 - 不能在普通異步 function 中使用鈎子?

[英]React hooks - Can't use hook inside plain async function?

我是鈎子的新手,到目前為止印象深刻,但是,如果我嘗試在 function 中使用鈎子,它似乎會抱怨(無效的鈎子調用。只能在 function 組件的主體內部調用鈎子。這可能發生以下原因之一)。

我在一個基本文件中有幾個常見的 API 函數,用於從 API 檢索數據。 他們不返回任何東西,只是將 (useDispatch) 發送到商店,並且使用此 state 的相關組件在整個應用程序中更新。 我知道這可能是原因,因為它沒有返回 React 元素,但有沒有辦法解決這個問題或更好、更“推薦”的 React 方法? 如果我必須手動傳入用戶並在父組件中調度返回的結果,這不是世界末日,但我寧願將它保存在一個地方並在這個 function 中處理它,所以所有父組件都有要做的是在 state 更改時進行更新。

這是 function:

export async function getCar(id) {

  // It's complaining about these hooks
  const { user } = useSelector(state => state.auth);
  const dispatch = useDispatch();

  try {
      let response = await axios.get(`${baseURL}api/cars/getCar/${id}/${user.id});
      if (response.data.successCode === 200) dispatch(setCar(response.data));
  } catch (error) {

  }
}

用法: const carsList = getCar("id");

謝謝大家,非常感謝。

掛鈎與 function 不同。 考慮到你想實現一個自定義鈎子,你首先需要在你的鈎子名稱前加上use

其次,鈎子不能返回異步值,除非您將其存儲在 state 中。 您還需要使用 useEffect function 以確保 api 請求僅被觸發一次或在更改 id 參數時觸發。

export function useGetCar(id) {
  // It's complaining about these hooks
  const { user } = useSelector(state => state.auth);
  const dispatch = useDispatch();
  useEffect(() => {
     async function myFn() {
        try {
              let response = await axios.get(`${baseURL}api/cars/getCar/${id}/${user.id});
              if (response.data.successCode === 200) dispatch(setCar(response.data));
        } catch (error) {

        }

      }
      fn()
  }, [id])
}

此外,由於您只是更新 state 您可以編寫另一個選擇器以從 redux 商店獲取汽車值

用法:

const Comp = ({id}) => {
    useGetCar(id);
    const car = useSelector(state => state.car);
}

鈎子是讓你“鈎入”React state 和 function 組件的生命周期特性的函數。 Hooks 在類中不起作用——它們讓你在沒有類的情況下使用 React。

你不能在if語句、函數、循環中放置鈎子, 它們也不能嵌套在任何東西中

鈎子只能在 function 組件主體的頂層內部調用。

閱讀官方文檔

我設法通過使用useCallback和 window 事件從普通的 javascript 觸發渲染。

// in the hooks file
export const useForceUpdate = () => {
  const [, setTriggerUpdate] = useState(0);
  const update = useCallback(() => {
    setTriggerUpdate((tick) => tick + 1);
  }, []);
  return update;
};
const handleMyOutsideCall= (
  callback: () => void
) => {
  window.addEventListener("myEvent", (e: CustomEvent) => {
    const data = e.detail;
    callback(data);
  });
};


export const dispatchMyOutsideCall = (name: string) => {
  const event = new CustomEvent("myEvent", {
    detail: {
      name: name,
    },
  });
  window.dispatchEvent(event);
};

// import useForceUpdate from hooks file 
export function MyComponent() {
  const {data, setData} = React.useContext(SomeContext);

  const update = useForceUpdate();
  useEffect(() => {
    handleMyOutsideCall(update);
  }, []);

  return <>App</>
}

然后在外部的一些其他es模塊中反應scope:

   // this will trigger state update on MyComponent
   dispatchMyOutsideCall("My_Test")

希望能幫助到你

暫無
暫無

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

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