反应钩子,ComponentDidMount

时间:2020-08-15 11:39:26

标签: reactjs react-hooks

在video.js的官方文档https://docs.videojs.com/tutorial-react.html

我们有

  componentDidMount() {
    // instantiate Video.js
    this.player = videojs(this.videoNode, this.props, function onPlayerReady() {
      console.log('onPlayerReady', this)
    });
  }

我想用挂钩创建功能组件

export default function VideoPlayer(props) {
  const player = useRef(null);
  const videoNode = useRef(null);
  useEffect(() => {
    player.current = videojs(videoNode.current, props);

    return () => {
      if (player.current) {
        player.current.dispose()
      }
    }
  }, []);//I have problem with dependency array
  return (
    <div data-vjs-player>
      <video ref={videoNode} className="video-js"/>
    </div>
  )
}

我有警告

ESLint:React Hook useEffect缺少依赖项:'props'。要么包含它,要么删除依赖项数组。(react-hooks / exhaustive-deps)

如果我将依赖项数组从[]更改为[props] useEffect在每个渲染上运行,我只想像componentDidMount那样第一次运行它

如何使用钩子精确创建componentDidMount

1 个答案:

答案 0 :(得分:1)

here所述,您按预期使用了useEffect。空的依赖项数组意味着它将仅运行一次(如componentDidMount)。指出的错误会通知您是否确实有其他意图,但效果不会再次呈现。

要消除此错误,您只需粘贴以下注释 // eslint-disable-line react-hooks/exhaustive-deps末尾的useEffect

useEffect(() => {
  player.current = videojs(videoNode.current, props);

  return () => {
    if (player.current) {
      player.current.dispose()
    }
  }
}, []); // eslint-disable-line react-hooks/exhaustive-deps

参考

answer对其进行了更详尽的解释