【问题标题】:React hook , ComponentDidMount [duplicate]反应钩子,ComponentDidMount [重复]
【发布时间】:2020-12-05 02:23:29
【问题描述】:

在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

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案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解释得更透彻

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 2019-06-21
      • 2019-08-07
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多