Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
Cómo actualizar el estado ancestral de un componente secundario profundamente anidado sin reductores

Tengo una aplicación de reacción con una estructura similar al siguiente código (pero más complejo). En realidad, todo lo que estoy cambiando son los datos en el componente nieto ( grandchild.name en este ejemplo). Sin embargo, tengo que pasar controladores getters (props) y setters (onChange) en todos los componentes a lo largo de la jerarquía, lo que lo hace innecesariamente complicado (especialmente si se agregan más componentes anidados (por ejemplo GreatGrandChild ).

 // Parent const Parent = () => { const [child, setChild] = useState({ name: 'Jack', grandChild: { name: 'John' } }); return ( <div> <Child data={child} onChange={newChild => setChild(newChild)} /> </div> ); }; // Child const Child = props => { const handleChange = newGrandChild => { props.onChange({ name: props.data.name, grandChild: newGrandChild }); }; return ( <div> <GrandChild data={props.data.grandChild} onChange={handleChange} /> </div> ); }; // Grand Child const GrandChild = props => { const handleChange = e => { props.onChange({ name: e.target.name }); }; return ( <div> <input type='text' onChange={handleChange} /> </div> ); };

Entonces, ¿cómo se puede actualizar el estado principal sin agregar la función handleChange en el componente secundario? Escuché que el "curring de funciones" puede resolver esto, pero no sé cómo usarlo en este caso.

PD: necesito una solución que no incluya Contextos y/o Reductores, ya que sería excesivo para mi caso de uso. Además, crear una función "updateGrandChild" en el padre y pasarla al componente nieto tampoco funcionará, ya que mi estructura de datos incluye una propiedad de matriz, donde el índice es dinámico.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

import { useState } from "react"; // Parent const Parent = () => { const [child, setChild] = useState({ name: "Jack", grandChild: { name: "John" } }); return ( <div> <pre>{JSON.stringify(child, null, 2)}</pre> <Child data={child} onChange={setChild} /> </div> ); }; // Child const Child = ({ data, onChange }) => { return ( <div> <GrandChild data={data.grandChild} onChange={onChange} /> </div> ); }; // Grand Child const GrandChild = ({ data, onChange }) => { return ( <div> <input type="text" value={data.name} onChange={(e) => onChange((data) => ({ ...data, grandChild: { ...data.grandChild, name: e.target.value } })) } /> </div> ); }; export default function App() { return <Parent />; }

Caja de códigos aquí

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!