如何解决反应钩子,ComponentDidMount
在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
?
解决方法
如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对其进行了更详尽的解释
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。