仅当道具更改时,如何在自定义钩子中触发useEffect?

How to make useEffect in custom hook trigger only when props changed?

在这个视频中,Dan 提取了一个 useDocumentTitle 自定义钩子,但我发现自定义钩子触发了多次,有时是不必要的。问题是如何只在key props改变时才触发useEffect函数?

不使用自定义钩子也可以这样实现:

useEffect(() => {
  console.log('useDocumentTitle ')

  document.title = myTitle);
}, [someProp])

但是如何使用自定义挂钩呢?

https://youtu.be/dpw9EHDh2bM?t=2969

您可以简单地将密钥作为单独的参数传递,并在自定义挂钩中使用上面使用的代码。

function useCustomHook({someProp, myTitle}) {
    useEffect(() => {
        console.log('useDocumentTitle ')

        document.title = myTitle);
    }, [someProp])
}

你会像这样使用它:

const customHookOptions = {someProp: props.key, myTitle: 'the title'}
useCustomHook(customHookOptions)

你能做的另一件事是 re-render 整个组件,如果 props 使用 react.memo() https://reactjs.org/docs/react-api.html#reactmemo

改变

还有一个钩子useMemo,它有自己的位置来做繁重的工作https://reactjs.org/docs/hooks-reference.html#usememo