React hook, ComponentDidMount [duplicato]
Nel documento ufficiale di video.js https://docs.videojs.com/tutorial-react.html
noi abbiamo
componentDidMount() {
// instantiate Video.js
this.player = videojs(this.videoNode, this.props, function onPlayerReady() {
console.log('onPlayerReady', this)
});
}
Voglio creare componenti funzionali con ganci
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>
)
}
Ho un avvertimento
ESLint: React Hook useEffect ha una dipendenza mancante: 'props'. Includilo o rimuovi l'array delle dipendenze. (React-hooks / Exclusive-deps)
Se cambio l'array delle dipendenze da []
a [props]
useEffect
viene eseguito su ogni rendering, voglio solo eseguirlo la prima volta, comecomponentDidMount
Come posso creare esattamente componentDidMount
usando gli hook?
Risposte
Come spiegato qui , hai usato useEffect
come previsto. Un array di dipendenze vuoto significa che verrà eseguito solo una volta (as componentDidMount
). L'errore segnalato ti informa che se avevi effettivamente altre intenzioni, l'effetto non verrà più riprodotto.
Per ignorare l'errore, puoi semplicemente incollare il seguente commento // eslint-disable-line react-hooks/exhaustive-deps
alla fine diuseEffect
useEffect(() => {
player.current = videojs(videoNode.current, props);
return () => {
if (player.current) {
player.current.dispose()
}
}
}, []); // eslint-disable-line react-hooks/exhaustive-deps
RIFERIMENTO
Questa risposta lo spiega in modo più approfondito