簡體   English   中英

未捕獲(承諾中)錯誤:無效的掛鈎調用。 - 特例

[英]Uncaught (in promise) Error: Invalid hook call. - SPECIAL CASE

我知道鈎子不能從 React 功能組件以外的函數調用,這有點不同。

我創建了一些需要使用鈎子的實用程序/服務類型函數。

// somewhere in services files...
const utilNavTo = (route) => {
    const navigate = useNavigate();
    ...
};

// somewhere in components for screens...
const MyScreen = () => {
   ...
   if(something){
      utilNavTo('/somewhere');
   }
   ...
};

// the main app is created with <App /> not App, so that should not be the reason of error
ReactDOM.render(<App />, document.getElementById("root"));

// also App is fully defined with routes having <MyScreen /> defined properly...

當在 React 功能組件中使用這樣的函數時,我收到此錯誤:

Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

如果我從 react 功能組件中調用鈎子並將其傳遞給實用程序函數,它就可以很好地工作。

有沒有辦法在不將鈎子作為參數傳遞的情況下完成這項工作? 我猜它應該只有在沒有從功能組件調用實用程序函數本身時才會失敗。

問題

這里的問題是代碼有條件地在回調函數中調用useNavigate 這打破了鈎子的規則

不要在循環、條件或嵌套函數中調用 Hook。 相反,在任何提前返回之前,始終在 React 函數的頂層使用 Hooks。 通過遵循此規則,您可以確保每次渲染組件時都以相同的順序調用 Hook。

解決方案

utilNavTo轉換為自定義的 React 鈎子,該鈎子返回一個供組件使用的函數。 鈎子應該在函數組件體中調用。

例子:

// somewhere in services files...
const useUtilNavTo = () => {
  const navigate = useNavigate();

  const utilNavTo = (route) => {
    ...
  };

  return utilNavTo;
};

...

// somewhere in components for screens...
const MyScreen = () => {
  const utilNavTo = useUtilNavTo();

  ...

  if(something){
    utilNavTo('/somewhere');
  }

  ...
};

暫無
暫無

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

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