React hook, ComponentDidMount [duplicato]

Aug 15 2020

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] useEffectviene eseguito su ogni rendering, voglio solo eseguirlo la prima volta, comecomponentDidMount

Come posso creare esattamente componentDidMountusando gli hook?

Risposte

1 DavidBuzatu Aug 15 2020 at 18:44

Come spiegato qui , hai usato useEffectcome 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-depsalla 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