我有幾個在其中重複調度的元件。我想使用輔助函數在多個元件中導入和使用。令人抓狂的是,這並不簡單——至少對我來說是這樣。閱讀了很多關於此的文章,但無法關聯它。
我遇到的問題是react-dom.development.js:16227 Uncaught Error: Invalid hook call。鉤子只能在函數元件的主體內部呼叫。發生這種情況可能是由於以下原因之一: 您可能違反了 Hooks 規則
那麼如何在輔助函數中呼叫調度呢?我認為自訂掛鉤可能是可行的方法 - 現在就看看它。
精簡元件範例:
...imports... import { helperCall } from '../../assets/helperFunctions/helperCall'; export default function CompExamp() { ...variables... return ( <div className="min-w-0 flex-1" onClick={(e) => helperCall(e, searchText, searchType)} > <span className="absolute inset-0" aria-hidden="true" /> <p className="text-sm font-medium text-black">Target</p> <p className="text-base text-gray-700">test</p> </div> ) }
精簡輔助函數:
import React from 'react'; import { useDispatch } from 'react-redux'; import { useNavigate } from 'react-router-dom'; import { loadASearchResults, updateASearchTerm } from '../../redux/actionsReducers/AResults'; import { loadBSearchResults, updateBSearchTerm } from '../../redux/actionsReducers/BResults'; import { loadCSearchResults, updateCSearchTerm } from '../../redux/actionsReducers/CResults'; export function helperCall(e: any, searchText: string, searchType: string) { const dispatch = useDispatch(); const navigate = useNavigate(); e.preventDefault(); e.stopPropagation(); if (!searchText || searchText === '-' || searchText.toLowerCase() === 'not listed') { return; } if (searchType === 'a') { dispatch(updateASearchTerm({ searchTerm, searchType })); dispatch(loadASearchResults({ searchTerm, searchType })); navigate('/page-a'); } else if (searchType === 'b') { dispatch(updateBSearchTerm({ searchTerm, searchType })); dispatch(loadBSearchResults({ searchTerm, searchType })); navigate('/page-b'); } else if (searchType === 'c') { dispatch(updateCSearchTerm({ searchTerm, searchType })); dispatch(loadCSearchResults({ searchTerm, searchType })); navigate('/page-c'); } }
您只能在 React 功能元件中使用 React hooks,但您可以將函數傳遞給輔助函數,如下所示: