reactjs / reactjs/react.dev

Controlled form components with async data

Abierto
#1,238 0 comentarios 1 reacción 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 like a pretty common scenario when implementing forms with React+Redux but neither documentation nor any of the articles/answers online seem to provide full implementation/recommendation.

Here's the scenario

  1. Data is loaded initially and passed to my <Form /> component.
class Form extends React.Component {
    constructor(props) {
        this.state = { nameField: props.name };
    }
    ...
}
  1. Initial data is rendered on the screen and state is used to track user input, making this a fully controlled component.
render() {
    return(
        <form>
            <input value={this.state.nameField} onChange={e => this.setState({ nameField: e.target.value })} />
        </form>
    );
}
  1. Data is then saved to the server asynchronously (here I'm using Redux but the same thing can be achieved with fetch, etc.):
handleSubmit(e) {
    e.preventDefault();
    const { dispatch } = this.props;
    dispatch(actions.saveData(...this.state);
}
  1. Reducers handle successful data save and the new state is saved. This data is then once again passed to my <Form /> component as props because the redux state is my single source of truth.

I now should update my component's state to match the application state (in case there were some external changes done on the server or parent component). Since in this case "fresh" props should always overwrite the state, one would normally use componentWillReceiveProps to simply set the new state but that method is now deprecated. The other two methods available - componentDidUpdate and getDerivedStateFromProps - could work BUT there needs to be a deep comparison of new props vs old props done in order to determine if the change is due to "fresh" props or just the internal state update. This can get very expensive if my form has 30 fields because both of these methods fire on each re-render.

I am trying to figure out the best practice in this scenario - should I delegate user input changes to Redux and avoid using component's state altogether? Or the only way now to make sure that the state stays in sync with props is to do a deep comparison of new pros vs old props on each re-render? Or is there another approach I'm not thinking of that works better?

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

El issue no menciona archivos del repositorio, pruebas ni puntos de entrada. Primero aclara si react.dev debería documentar formularios controlados con datos cargados de forma asíncrona y define las indicaciones previstas; el resultado debería ser una documentación que responda al escenario descrito de React y Redux.

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

Evaluación

Stack tecnológico
javascript, react
Área
documentation
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
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.