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

131
Vistas
El gancho useEffect no se llama en los cambios de accesorios.

Tengo 2 menús desplegables, necesito actualizar los valores del segundo menú desplegable en función del primero. En la carga de la página, necesito inicializar los valores desplegables según las condiciones, así:

 const getInitialState= () => { //defaultSelected has a value if saved in DB, if not then I set the 0 option value in type, based on this value option value will be populated in the dropdown. I get all the values from parent component let updatedType= defaultSelected !== "" ? defaultType : Region.RegionType; console.log('typeeeee', type) return updatedType; } useEffect(() =>{ //Here in options dropdown values object is set based on type selected let updatedOptions = !_.isEmpty (type) ? "a" //value from db if save : "b"; //If not 0th value of the object setOptions(prevOptions => ({ ...prevOptions, ["options"]: updatedOptions })); },[type]); const [type, setType] = useState(getInitialState); const [options, setOptions] = useState(''); const changeCrTypeHandler = (event) =>{ const { name, value } = event.target; setType(type =>({ ...type, [name]: value})); } return ( <> <select onChange={changeCrTypeHandler} style={{ width: "150px" }} value={!_.isEmpty(type)} name= "type" > {_.map(customMap, (crId) => { //I get this cusomMap from Parent component return ( <option id={crId.customType} value={crId.customType} key={crId.customType} > {crId.customType} </option> ); })} </select>{" "} &nbsp; &nbsp;&nbsp; &nbsp; <select onChange={changeCrHashHandler} //second dropdown onchange style={{ width: "250px" }} value={crHashId} name= "options" > {_.map(!_.isEmpty(options), (o) => { //This options are created based on type, which is currently not getting set return ( <option id={o.customId} value={o.customId} key={o.customId} > {o.name} </option> ); })} </select>

Según el valor del tipo, necesito establecer el valor de la opción.

Pero mi gancho useEffect no recibe cambios en el tipo. ¿Cómo puedo llamar al método useEffect siempre que haya cambios en el tipo?

Cualquier ayuda para esto sería muy apreciada.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Está llamando a setState antes de que se defina. Para el valor inicial, simplemente lo devuelve sin llamar a setState . Para tener el segundo estado desplegable dependiendo del estado del primero, puede usar el gancho useEffect , así:

 const [firstDropdown, setFirstDropdown] = useState(getInitialState({type:"", options:""})); const [secondDropdown, setScondDropdown] = useState(0); // you could use whatever initial value you want here const getInitialState= () => { //some logic to get the value in type //just return that inital value without calling setState } // the function inside useEffect runs every time firstDropdown changes useEffect(()=>{ // some logic on firstDropdown let value = firstDropdown+25 setScondDropdown(value) },[firstDropdown]);

Actualizar :

En su useEffect , cambie esto:

 setOptions(prevOptions => ({ ...prevOptions, ["options"]: updatedOptions }));

a esto :

 setOptions(updatedOptions)
about 4 years ago · Juan Pablo Isaza Denunciar

0

Use el useState como se muestra a continuación:

 const [state, setState] = useState({}) setState((prev) => { // do whatever you want to do with the previous state })

Y para el nombre, no use setState como su función de establecimiento de useState. porque setState es otro método en los componentes basados en clases en React

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