如何编写带有调用函数的 React 钩子?

How to write React hooks with called functions?

我有一个 useQuery() 钩子:

const useQuery = () => {
  const router = useRouter();
  const build = (query) => {}
  const read = () => {}
}
export default useQuery;

我希望能够在我的代码中使用 hook,例如:

const query = useQuery();

useEffect(()=>{
  const oldQuery = query.read();
  if(oldQuery.length === 0) query.build(newQuery);
},[])

但每次我尝试调用 query.read() 时都会收到错误 Property 'read' does not exist on type 'void'. 看起来像是范围问题。我该如何解决?

您需要 return 语句 useQuery:

const useQuery = () => {
  const router = useRouter();
  const build = (query) => {}
  const read = () => {}

  return { router, build, read }
}

您可能还想考虑记忆这些函数,这样使用这个钩子的代码就不会因为认为函数已经改变而做不必要的工作:

const build = useCallback((query) => {}, []);
const read = useCallback((() => {}, []);