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

96
Views
Reemplazar ganchos useState dentro de un objeto
 const [country, setCountry] = useState(""); const [city, setCity] = useState(""); const [population, setPopulation] = useState(""); const [location, setLocation] = useState(""); const [temp_min, setTmep_min] = useState("");

Oye, alguien tiene alguna idea de cómo reemplazar estos ganchos useState de una manera efectiva y limpiar el código como ponerlos todos en un objeto en lugar de inicializarlo con el nuevo useState.

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

0

Puede usar useReducer en su lugar. Esto le permitiría inicializar el estado con un objeto. Además, ahora puede usar el dispatch para todas las actualizaciones, aunque deberá pasarle un objeto con la propiedad que desea actualizar.

 const reducer = (state, update) => ({ ...state, ...update, }); const [state, dispatch] = useReducer({ country: '', city: '', population: '', location: '', temp_min: '' });

Ejemplos:

 dispatch({ country: 'Spain' }); // setting a country dispatch({ city: 'Madrid' }); // setting a city
about 4 years ago · Juan Pablo Isaza Report

0

Puedes hacer un useState como este

 const [obj, setObj] = useState({ country: "", City: "", Population: "", Location: "", temp_min: "" })
about 4 years ago · Juan Pablo Isaza Report

0

Implementé el gancho useReducer para poner todas estas propiedades en un objeto simple (que es mejor para componentes con estados complejos) y también usé algunas validaciones para evitar errores al actualizar el estado cuando el componente está desmontado, por ejemplo:

 const App: React.FC = () => { const initialState = { name: '', password: '' }; const { state, onUpdateValue, // Update a value from the dictionary onClearValue // Remove a value from the dictionary onClear // Remove all values from the dictionary } = useDictionary(initialState); const onSubmit = useCallback((event: React.FormEvent) => { event.preventDefault(); console.log('Create User!', state); onClear(); }, [state]); return ( <form onSubmit={onSubmit}> <label> Name: <input type="text" value={state.name} onChange={(e) => onUpdateValue('name', e.target?.value)} /> </label> <label> Password: <input type="password" value={state.password} onChange={(e) => onUpdateValue('password', e.target?.value)} /> </label> <input type="submit" value="Submit" /> </form> ); }

Link del repositorio: https://github.com/proyecto26/use-dictionary

¡Feliz codificación! <3

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!