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

264
Views
Cómo usar solo 1 useState () para varios estados

Tengo un componente de reacción que usa varios estados que se inicializan de la misma manera useState (falso), ¿hay alguna manera de combinar todos estos estados en un solo useState (falso)?

 const [loading, setLoading] = useState(false); const [fields, setFields] = useState(false); const [wrongImageType, setWrongImageType] = useState(false); const [aboutError, setAboutError] = useState(false); const [destinationError, setDestinationError] = useState(false)
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Puedes hacer esto

 const [states, setStates] = useState({ loading:false, fields:false, wrongImageType:false, aboutError:false, destinationError:false })

Estado de actualización como este

 setStates((prevState) => ({ ...prevState, loading: true }))
about 4 years ago · Juan Pablo Isaza Report

0

Usualmente uso el gancho useReducer . De esa manera, puedo simplemente asignar propiedades a algún objeto de estado y el reductor lo arregla todo para mí. También facilita las cosas cuando tengo que enviar un objeto a una API, solo arrojo todo el objeto de state al servidor. Entonces, básicamente es "obtener datos del servidor, usar entradas de formulario para permitir que el usuario actualice los valores, devolver los datos al servidor cuando hacen clic en el botón Guardar".

 import React, { useReducer, useEffect } from "react"; const initialState = { loading: false, fields: false, wrongImageType: false, aboutError: false, destinationError: false }; const reducer = (prev, cur) => ({ ...prev, ...cur }); const MyComponent = () => { const [state, setState] = useReducer(reducer, initialState); useEffect(() => { setState({ loading: true }); // fetch something or do something... setState({ loading: false }); }, []); return ({ state.loading ? <> Loading </> : <>{state.something}</> }); }

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!