You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  • handleHide doesn't update state: Right now, it just returns a filtered array but never updates the companies state 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's onClick prop, which means this function runs immediately when the component renders, not when the button is clicked.
  • Confused modal state: You have both showModal and show states 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

  1. Simplified Modal State: Removed the redundant show state and used a single showModal state to manage modal visibility, eliminating confusion.
  2. Functional State Update in handleHide:
    • Uses prevCompanies => ... to safely access the latest state before filtering, which avoids race conditions.
    • Updates the companies state with the filtered array, triggering the table to re-render without the hidden row.
  3. Correct OnClick Binding: Passed the handleHide function reference instead of calling it immediately, so it only runs when the button is clicked.
  4. Safety Checks: Added optional chaining (modalInfo?.name) and conditional rendering to prevent errors if the modal opens before modalInfo is populated.
  5. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 15:48:12