reactjs / reactjs/react.dev

Lifecycle with updates at multiple hierarchy levels

Abierto
#1,210 7 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Lenguaje dominante
JavaScript
Estrellas
11.8k
Forks
7.9k
Merge medio
1 d 11 h
PR fusionados (30 d)
11

Descripción

This seems to be a particular lifecycle that wasn't considered when making the componentWillReceiveProps function deprecated. Or, perhaps I just cannot find a built-in way in React on how to do this properly. In either case, some guidance would be highly appreciated.

In my project, a top-level component fetches data from a service and then passes it, when received, to lower-level components as props (i.e., the higher-level component is fully controlled). These lower-level components are fields that display the retrieved data, and allow adding and removing data items afterwards. Clearly, these operations need to be reflected in the state (and also sent to the restful service, but this is inconsequential here). Hence, it would make sense to make the state the "single source of truth" since the data could be updated by the lower-level component ("field" from now on) at any point, requiring a re-render each time (?)

When first creating the field (i.e., in the constructor), this data is not yet available, since it's fetched from the service. This means that a method such as componentWillReceiveProps or getDerivedStateFromProps should be used to derive the initial state from the props (?) Since componentWillReceiveProps is deprecated I recently tried replacing it with getDerivedStateFromProps. However, this function is called "on every render, regardless of the cause" (e.g., because of a state change), instead of componentWillReceiveProps "which only fires when the parent causes a re-render" (see here). Hence, any local state change (e.g., removing a data item) will also cause the getDerivedStateFromProps function to be called (including ones caused by getDerivedStateFromProps ...).

Currently, to differentiate between state & props updates, I introduced the following function, which only derives the state from the props once, and, after any local state change, will ignore changes in props. The function is called from the field's getDerivedStateFromProps function (ignoreFunction depends on the particular field, and returns whether state and props include the same data). Note that a local state change involves setting an update field to true in the state.

static getGroundStateFromProps(props, state, ignoreFn) {
    // nothing in state or props was updated
    if (ignoreFn(state, props))
      return null

`    // some relevant update occurred; either state or props
    else {
      // in case state has been updated once, consider it "ground truth"
      if (state.updated)
        return null
      else
        return { values: props.values }
    }
  }

Would this be a suitable pattern to deal with this issue?

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Revisa la documentación del ciclo de vida de los componentes de React enlazada en el issue, especialmente componentWillReceiveProps y getDerivedStateFromProps, junto con el flujo descrito entre el parent controlado y el child editable localmente. Aclara el patrón compatible para recibir props asíncronas mientras se conservan las actualizaciones del child, y documenta una guía que distinga entre los cambios de estado impulsados por props y los cambios de estado locales. Se considera terminado cuando el escenario tenga un enfoque recomendado explícito sin depender del comportamiento obsoleto del lifecycle.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
javascript, react
Área
documentation, frontend
Tipo de issue
Documentación
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Necesita aclaración
Aptitud para principiantes
30/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.