reactjs / reactjs/react.dev

React docs on useEffect

Aperta
#2,919 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Lingua principale
JavaScript
Stelle
11.8k
Fork
7.9k
Merge medio
1g 11h
PR unite (30g)
11

Descrizione

The docs have an example about using useEffect with cleanup, here.

If I carry out the sequence, then I would get
run effect -> subscribe to update from ChatApi -> setIsOnline -> cleanup -> run effect -> subscribe to update from ChatApi -> setIsOnline

I am unsure as to why this does not lead to an infinite loop without use of the dependency array?

One understanding / theory that I have is:
The first time the subscription cause setIsOnline(true). Next time (after one cycle of unsubscribe/effect), the setIsOnline gets argument as true and hence further update to the component does not occur. This is assuming that this form of setIsOnline does not re-render if the isOnline has not changed (it is still true).

I am curious as to why the piece of code is correct.

Here it is as copied from the useEffect documentation

import React, { useState, useEffect } from 'react';

function FriendStatus(props) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    // Specify how to clean up after this effect:
    return function cleanup() {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia con l’esempio collegato nella documentazione di useEffect e rivedi la sequenza descritta di sottoscrizione, cleanup e setIsOnline. Chiarisci se l’esempio necessita di una spiegazione del suo comportamento di rerender o di un esempio rivisto, quindi aggiorna la documentazione in modo che il ciclo di vita previsto dell’effect e i criteri di completamento siano espliciti.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
javascript, react
Ambito
documentation
Tipo di issue
Documentazione
Difficoltà
3/5
Tempo stimato
1-2 giorni
Stato di attività
Ferma
Chiarezza
Da chiarire
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.