简体   繁体   English

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

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

In this video, Dan extract a useDocumentTitle custom hook, but I found the custom hook trigger multiple times, sometimes it is unnecessary.在这个视频中,Dan 提取了一个 useDocumentTitle 自定义钩子,但我发现自定义钩子触发了多次,有时是不必要的。 The question is how to trigger the useEffect function only when the key props changed?问题是如何只在key props改变时触发useEffect函数?

It could be realized like this without using custom hooks:可以在不使用自定义钩子的情况下像这样实现:

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

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

But how to do it with custom hooks?但是如何使用自定义钩子来做到这一点?

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

You can simply pass the key as a separate argument and have the code you used above in the custom hook.您可以简单地将密钥作为单独的参数传递,并在自定义钩子中包含您在上面使用的代码。

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

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

you would use it like:你会像这样使用它:

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

Another thing you are able to do is only re-render the entire component if props change by using react.memo() https://reactjs.org/docs/react-api.html#reactmemo您可以做的另一件事是仅在道具更改时使用react.memo() https://reactjs.org/docs/react-api.html#reactmemo重新渲染整个组件

There is also a hook useMemo which has it's own place for doing heavy work https://reactjs.org/docs/hooks-reference.html#usememo还有一个钩子useMemo ,它有自己的地方来做繁重的工作https://reactjs.org/docs/hooks-reference.html#usememo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM