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

539
Views
Reaccionar: Actualizar componente sin recargar después de eliminar un elemento

En mi aplicación React, estoy mostrando todos los libros con el nombre del autor. El usuario puede eliminar un libro haciendo clic en un elemento. La cosa es que quiero actualizar la página sin recargar toda la página. Los estados son el camino a seguir para este tipo de situaciones, pero aún así no actualiza el componente.

¿Alguien puede sugerir alguna idea?

Aplicación.tsx

 import React, { useLayoutEffect, useState } from "react"; import { BrowserRouter, Route, Routes } from "react-router-dom"; import { getAllBooks } from "./api_actions/api_calls"; import "./App.css"; import AllBooks from "./components/AllBooks"; import InsertBooks from "./components/InsertBook"; import { Book } from "./models/Book"; function App() { const [myBooks, setMyBooks] = useState<Book[]>([]); useLayoutEffect(() => { getAllBooks().then((orders) => { setMyBooks(orders); }); }, []); return ( <div className="App"> <header className="App-header"> <BrowserRouter> <Routes> <Route path="/" element={<AllBooks books={myBooks} />} /> <Route path="/add" element={<InsertBooks />} /> </Routes> </BrowserRouter> </header> </div> ); } export default App;

Componente que muestra todos los libros, AllBooks.tsx:

 interface IAllBooksProps { books: Book[]; } const AllBooks: React.FC<IAllBooksProps> = (props) => { const [lastDeletedTitle, setLastDeletedTitle] = useState(""); const handleDeleteBook = (title: string) => { console.log("Trying to delete...", title); deleteBook(title).then((response) => { setLastDeletedTitle(title); }); }; useEffect(() => { if (lastDeletedTitle !== "") { toast(`${lastDeletedTitle} has been deleted!`); } }, [lastDeletedTitle]); return ( <> {props.books?.map((book) => { return <Card key={book.id} book={book} onDelete={handleDeleteBook} />; })} <ToastContainer /> </> ); };
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Trae cambios en AllBooks.tsx como abajo

 const AllBooks: React.FC<IAllBooksProps> = (props) => { const [books, setBooks] = useState(props.books); //props.books set in books state const [lastDeletedTitle, setLastDeletedTitle] = useState(""); const handleDeleteBook = (title: string) => { console.log("Trying to delete...", title); deleteBook(title).then((response) => { setLastDeletedTitle(title); }); }; useEffect(() => { if (lastDeletedTitle !== "") { toast(`${lastDeletedTitle} has been deleted!`); //recall the getAllBooks here getAllBooks().then((orders) => { setBooks(orders); //reset books }); } }, [lastDeletedTitle]); return ( <> //return books here {books?.map((book) => { return <Card key={book.id} book={book} onDelete={handleDeleteBook} />; })} <ToastContainer /> </> ); };
about 4 years ago · Juan Pablo Isaza Report

0

Es mejor no llamar a getAllBooks en App.tsx . Solo necesita llamar a getAllBooks dentro de su función de delete y useEffect en AllBooks.tsx . Pruebe el código que se proporciona a continuación,

Todos los libros.tsx

 interface IAllBooksProps { books: Book[]; } const AllBooks: React.FC<IAllBooksProps> = (props) => { const [lastDeletedTitle, setLastDeletedTitle] = useState(""); useEffect(() => { getBooks(); }, []) const getBooks = () => { getAllBooks().then((orders) => { setMyBooks(orders); }); } const handleDeleteBook = (title: string) => { console.log("Trying to delete...", title); deleteBook(title).then((response) => { setLastDeletedTitle(title); getBooks(); }); }; useEffect(() => { if (lastDeletedTitle !== "") { toast(`${lastDeletedTitle} has been deleted!`); } }, [lastDeletedTitle]); return ( <> {props.books?.map((book) => { return <Card key={book.id} book={book} onDelete={handleDeleteBook} />; })} <ToastContainer /> </> ); };
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!