在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
?
答案 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对其进行了更详尽的解释