Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

133
Vistas
Actualizar objetos anidados en React Native usando setState

Estoy tratando de cambiar las propiedades de los objetos dentro de un objeto y tratando de agregar nuevas propiedades a estos objetos pero manteniendo los valores anteriores.

No puedo averiguar cómo obtener el objeto anidado correcto por índice, no por identificación porque la identificación puede ser diferente del índice .map.

Esto es lo que obtuve hasta ahora, los nombres de los objetos son solo para fines de prueba y tal vez el "updateNestedObject" se pueda ejecutar en el padre.

Gracias de antemano y disculpe si es una pregunta de novato.

Neval

 import React, { useState } from 'react'; import { View, TextInput, Text, StyleSheet, Button, Alert } from 'react-native'; function ObjectScreen() { const [state, setState] = useState({ id: 1, name: 'Test Object', nested: [ { id: 1, title: 'Object 1', }, { id: 2, title: 'Object 1', } ] }); function editNested({nestedObject, index, setState}) { const updateNestedObject = () => { setState(prevState => ({ nested: [ ...prevState.nested, [prevState.nested[index].comment]: 'Test Comment', }, })); } return ( <View> <Text>{object.title}</Text> <TextInput style={styles.input} name="comment" onChangeText={updateNestedObject} /> </View> ); } return ( <> <Text>{state.name}</Text> { state.nested.map((nestedObject, key)=>{ return ( <editNested key={key} index={key} object={object} nestedObject={nestedObject}/> ) })} </> ) } const styles = StyleSheet.create({ container: {}, input: { height: 40, margin: 12, borderWidth: 1, padding: 10, }, }); export default ObjectScreen;
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Según la cola, puede actualizar la matriz anidada con el siguiente método

 const updateNestedObject = (values, item, index) => { console.log('values', values); const tempMainObj = state; const tempArr = state.nested; tempArr[index].value = values; const updatedObj = { ...tempMainObj, nested: tempArr }; setState(updatedObj); };

Ejemplo completo

 import React, { useState } from 'react'; import { View, TextInput, Text, StyleSheet, Button, Alert } from 'react-native'; function ObjectScreen() { const [state, setState] = useState({ id: 1, name: 'Test Object', nested: [ { id: 1, title: 'Object 1', value: '', }, { id: 2, title: 'Object 1', value: '', }, ], }); const updateNestedObject = (values, item, index) => { console.log('values', values); const tempMainObj = state; const tempArr = state.nested; tempArr[index].value = values; const updatedObj = { ...tempMainObj, nested: tempArr }; setState(updatedObj); }; return ( <> <Text style={{ marginTop: 50 }}>{state.name}</Text> {state.nested.map((item, index) => { return ( <> <Text>{item.title}</Text> <TextInput value={item?.value} style={styles.input} name="comment" onChangeText={(values) => updateNestedObject(values, item, index)} /> </> ); })} </> ); } const styles = StyleSheet.create({ container: { marginTop: 50, }, input: { height: 40, margin: 12, borderWidth: 1, padding: 10, }, }); export default ObjectScreen;

Exposición de bocadillos: ejemplo en vivo

about 4 years ago · Juan Pablo Isaza Denunciar

0

Hubo algunos problemas:

  1. El nombre del componente JSX editNested debe comenzar con una letra mayúscula.

  2. Y el componente editNested debe tener su propia función, no debe definirse dentro de otro componente que haya causado que su TextInput pierda el foco después de cada ciclo de procesamiento.

  3. La llamada setState debe cambiarse como se muestra a continuación:

 const updateNestedObject = (text) => { setState((prevState) => ({ ...prevState, nested: prevState.nested.map((item) => item.id === nestedObject.id ? { ...item, value: text } : item ) })); };

Pruebe el siguiente código:

 import React, { useState } from "react"; import { View, TextInput, Text, StyleSheet, Button, Alert } from "react-native"; function EditNested({ nestedObject, setState }) { const updateNestedObject = (text) => { setState((prevState) => ({ ...prevState, nested: prevState.nested.map((item) => item.id === nestedObject.id ? { ...item, value: text } : item ) })); }; return ( <View> <Text>{nestedObject.title}</Text> <TextInput style={styles.input} onChangeText={updateNestedObject} value={nestedObject.value} /> </View> ); } function ObjectScreen() { const [state, setState] = useState({ id: 1, name: "Test Object", nested: [ { id: 1, title: "Object 1", value: "" }, { id: 2, title: "Object 1", value: "" } ] }); console.log(state); return ( <> <Text>{state.name}</Text> {state.nested.map((nestedObject, key) => { return ( <EditNested key={key} nestedObject={nestedObject} setState={setState} /> ); })} </> ); } const styles = StyleSheet.create({ container: {}, input: { height: 40, margin: 12, borderWidth: 1, padding: 10 } }); export default ObjectScreen;

Demostración de trabajo

Editar goofy-river-uy5z9e

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda