React实现表格行点击弹窗后隐藏对应行功能的问题求助
Hey there! Let's fix that "Hide Element" functionality for your React table. I spotted a couple of issues in your code that are keeping it from working correctly—let's walk through them and get it sorted.
Key Issues in Your Current Code
handleHidedoesn't update state: Right now, it just returns a filtered array but never updates thecompaniesstate that your table relies on. The table has no way to know it should remove the row.- Incorrect onClick binding: You're calling
handleHide(modalInfo.id)directly in the Button'sonClickprop, which means this function runs immediately when the component renders, not when the button is clicked. - Confused modal state: You have both
showModalandshowstates handling modal visibility, which is unnecessary and causing inconsistent behavior.
Fixed Code
import React, { useEffect, useState } from 'react'; import axios from 'axios'; import BootStrapTable from "react-bootstrap-table-next" import paginationFactory from 'react-bootstrap-table2-paginator'; import {Modal , Button} from "react-bootstrap" import { useHistory } from "react-router-dom"; import Footer from "./Footer" export default function DataTable (){ const history = useHistory(); const [companies,setCompanies] = useState([]); const [modalInfo,setModalInfo] = useState(null); // Use null for single row context const [showModal, setShowModal] = useState(false); // Single state for modal visibility const getCompaniesData = async () =>{ try{ const data = await axios.get("http://localhost:5000/companies") setCompanies(data.data) } catch(e){ console.log(e) } } useEffect(()=>{ getCompaniesData(); },[]) const columns = [ {dataField:"id",text:"id"}, {dataField:"name",text:"name"}, ] const rowEvents = { onClick : (e,row)=>{ setModalInfo(row) setShowModal(true); // Directly toggle modal visibility } } const handleDetails = () =>{ history.replace('/details', {details:modalInfo}) setShowModal(false); // Close modal after navigating } const handleHide = () => { // Filter out the target row and update state setCompanies(prevCompanies => prevCompanies.filter(item => item.id !== modalInfo.id)); setShowModal(false); // Close modal after hiding the row }; return ( <div> <h1 className="text-center">Share-work Data Table</h1> <div className="table-back"> <BootStrapTable keyField="id" data={companies} columns={columns} pagination={paginationFactory()} rowEvents={rowEvents} /> <Footer/> </div> <Modal show={showModal} onHide={() => setShowModal(false)}> <Modal.Header closeButton> <Modal.Title>{modalInfo?.name}</Modal.Title> {/* Optional chaining to avoid null errors */} </Modal.Header> <Modal.Body> {modalInfo && ( // Only render content if modalInfo exists <> <h1>Company Details :</h1> <ul> <li>source_id : {modalInfo.source_id}</li> {/* Fixed list element type */} <li>source_name : {modalInfo.source_name}</li> <li>name : {modalInfo.name}</li> <li>city : {modalInfo.city}</li> <li>country : {modalInfo.country}</li> </ul> </> )} </Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={handleDetails}>Full Details</Button> <Button className="btn btn-danger" onClick={handleHide}>Hide Element</Button> </Modal.Footer> </Modal> </div> ) }
Key Fixes Explained
- Simplified Modal State: Removed the redundant
showstate and used a singleshowModalstate to manage modal visibility, eliminating confusion. - Functional State Update in
handleHide:- Uses
prevCompanies => ...to safely access the latest state before filtering, which avoids race conditions. - Updates the
companiesstate with the filtered array, triggering the table to re-render without the hidden row.
- Uses
- Correct OnClick Binding: Passed the
handleHidefunction reference instead of calling it immediately, so it only runs when the button is clicked. - Safety Checks: Added optional chaining (
modalInfo?.name) and conditional rendering to prevent errors if the modal opens beforemodalInfois populated. - Fixed List Markup: Replaced
<ol>with<li>in the modal body—<ol>is for ordered lists, while<li>is the correct element for items inside a<ul>.
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

