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

118
Views
Mostrar Toast sin usar useEffect para controlar el estado en reaccionar

Traté de agregar Toast de react-bootstrap en mi aplicación y puedo hacer que la funcionalidad funcione con el siguiente código. Sin embargo, me pregunto si es redundante usar useEffect para configurar show by setShow(items.length > 0); ? ¿Sería más fácil hacer algo como const show = items.length > 0; o alguna mejor manera para que me acerque?

 example of fetch response { "items": [ { "id": 1, "name": "Apples", "price": "$2" }, { "id": 2, "name": "Peaches", "price": "$5" } ] } import "./styles.css"; import React, { useState, useEffect } from "react"; import { Toast } from "react-bootstrap"; export default function App() { const [error, setError] = useState(null); const [show, setShow] = useState(false); const [items, setItems] = useState([]); useEffect(() => { fetch("https://api.example.com/items") .then((res) => res.json()) .then( (result) => { setItems(result); }, (error) => { setError(error); } ); }, []); useEffect(() => { setShow(items.length > 0); }, [items]); // const show = items.length > 0? maybe? const toggleShowB = () => setShow(!show); return ( <div className="App"> <Toast onClose={() => setShow(false)} show={show} delay={3000} autohide> <Toast.Header /> <Toast.Body>Woohoo, you're reading this text in a Toast!</Toast.Body> </Toast> </div> ); }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

esta es una buena pregunta

Analicemos el orden de las operaciones para lo que tienes:

  1. En el montaje, el primer useEffect buscará y llamará a setItems

  2. Este cambio de estado activará una nueva representación y actualizará items

  3. El segundo useEffect se ejecutará ya items son una dependencia y llamarán a setShow .

  4. Este es otro cambio de estado y activará una nueva representación para actualizar el show .

  5. Luego se mostrará su Toast (si items.length > 0 )

Alternativamente, sin el segundo efecto

  1. En el montaje, el primer useEffect buscará y llamará a setItems

  2. Este cambio de estado activará una nueva representación y actualizará items

  3. Tu Toast se mostrará si show={items.length > 0}

Conclusión

Se ahorra una nueva representación al no usar el segundo useEffect para actualizar una variable de estado de show .

about 4 years ago · Juan Pablo Isaza Report

0

En lugar de usar otro gancho useEffect, puedes simplemente usar:

 <Toast onClose={() => setShow(false)} show={items.length > 0 && show} delay={3000} autohide>

Puede forzar su cierre cambiando el programa. Esto funciona porque reaccionar lo vuelve a renderizar cada vez que cambia un items .

Editar

si no desea cerrarlo a la fuerza, simplemente elimine el && show.

 <Toast show={items.length > 0} delay={3000} autohide>
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!