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

React Modal映射数组渲染全部项而非对应ID单条数据问题

问题根因

出现全量渲染的核心原因有两点:

  • 点击表格行的View按钮时,没有捕获、传递当前点击行的对应数据
  • Modal渲染逻辑直接遍历整个submitted数组做全量map,没有针对当前点击行做匹配过滤
修复方案

1. 补充选中行状态

在原有弹窗显隐状态的基础上,新增状态存储当前点击的行数据,同时优化关闭弹窗的逻辑,避免残留旧数据:

const [showModal, setShow] = useState(false);
// 新增:存储当前激活的行数据
const [currentRow, setCurrentRow] = useState(null);

const handleClose = () => {
  setShow(false);
  // 关闭弹窗时清空选中行
  setCurrentRow(null);
};

2. 修改表格按钮的点击逻辑

react-bootstrap-table-next的formatter配置默认接收当前行数据作为第二个参数,点击按钮时先把当前行数据存入状态,再触发弹窗打开:

const columns = [
  { 
    dataField: "View", 
    text: "View", 
    formatter: (_, row) => {
      return (
        <Button 
          variant="success" 
          onClick={() => {
            setCurrentRow(row);
            setShow(true);
          }}
        >
          View
        </Button>
      )
    },
    headerStyle: () => ({ width: "5%" }) 
  },
  { 
    dataField: "BusinessName", 
    text: "Business Name", 
    headerStyle: () => ({ width: "27%" }) 
  },
];

3. 调整Modal渲染逻辑

去掉全量遍历submitted数组的map写法,直接渲染已存储的当前行数据,增加非空判断避免初始状态下的空值报错:

<Modal 
  show={showModal} 
  onHide={handleClose}
  size="lg" 
  centered
>
  <Modal.Header closeButton>
    {currentRow && <Modal.Title>{currentRow.BusinessName}</Modal.Title>}  
  </Modal.Header>
  <Modal.Body>
    {/* 其余详情字段直接从currentRow中取值即可,例如 <p>统一社会信用代码:{currentRow.CreditCode}</p> */}
  </Modal.Body>
  <Modal.Footer>
    <Button variant="secondary" onClick={handleClose}>
      Close
    </Button>
    <Button variant="primary" onClick={handleClose}>
      Save Changes
    </Button>
  </Modal.Footer>
</Modal>
可选优化

如果不想存储整行数据,也可以只存储当前点击行的唯一ID,Modal渲染时从submitted数组中匹配对应项即可,适合单条数据字段较多、数据量较大的场景:

// 状态只存当前行ID
const [currentRowId, setCurrentRowId] = useState(null);
// 渲染前匹配对应数据
const currentRow = submitted.find(item => item.Id === currentRowId);

内容的提问来源于stack exchange,提问作者It hurts when IP

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 07:01:09