如何在useEffect

时间:2020-03-03 18:05:19

标签: reactjs typescript react-hooks

我正在构建一个自定义钩子,我想在该钩子中向引用添加事件侦听器,但是由于listReflistRef.current可能为null,因此我不确定如何正确清理:

export const myHook: MyHook = () => {
  const listRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    // I can check for the presence of `listRef.current` here ...
    if (listRef && listRef.current) {
      listRef.current.addEventListener(...)
    }

    // ... but what's the right way for the return function?
    return listRef.current.removeEventListener(...)
  })

  return [listRef]
}

1 个答案:

答案 0 :(得分:2)

编辑:

但是我还必须检查return函数中是否存在listRef,对吧?

是的,您可以做的是将一切都包裹在if语句中

  useEffect(() => {
    // Everything around if statement
    if (listRef && listRef.current) {
      listRef.current.addEventListener(...)

      return () => {
        listRef.current.removeEventListener(...)
      }
    }
  })

如果您不致电addEventListener,则无需致电removeEventListener,因此将所有内容都放在if内的原因。


您需要在返回中传递一个函数,该函数可以执行清除操作。

export const myHook: MyHook = () => {
  const listRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    // This is ok
    if (listRef && listRef.current) {
      listRef.current.addEventListener(...)
    }

    // Passing a function that calls your function
    return () => {
        listRef.current.removeEventListener(...)
    }
  })

  return [listRef]
}

您需要注意的另一件事是,在fooEventListener内部,...应该是该函数的相同引用,这意味着:

您不应这样做:

  useEffect(() => {
    if (listRef && listRef.current) {
      listRef.current.addEventListener(() => console.log('do something'))
    }

    return () => {
        listRef.current.removeEventListener(() => console.log('do something'))
    }
  })

您应该这样做:

  useEffect(() => {
    const myFunction = () => console.log('do something')

    if (listRef && listRef.current) {
      // Passing the same reference
      listRef.current.addEventListener(myFunction)
    }

    return () => {
      // Passing the same reference
      listRef.current.removeEventListener(myFunction)
    }
  })