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

React中如何实现表格加载与搜索时使用不同数据集?

问题:表格加载与搜索时切换不同数据集

场景

  • 页面加载时,表格渲染userDataA数据集
  • 用户在搜索栏输入内容时,触发change事件调用搜索函数
  • 搜索函数遍历数据,隐藏不符合搜索条件的行
  • 用户清空搜索栏后,表格恢复显示全部数据

现有代码

搜索功能

function myFunction() {
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }       
  }
}

表格组件

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Country</th>
  </tr>
  <tbody>
         {userDataA.map(key, value) {
             <td>{value}</td>
             <td>{key}</td>
         }}
  </tbody>
</table>

需求

实现表格加载时用userDataA,搜索时切换为userDataB进行筛选,清空搜索后切回userDataA。

尝试过的方法及问题

  1. 布尔值JSX条件判断
<tbody>
         {searchIsPerformed === true ? dataToReadFrom = userDataB : userDataA}
         {dataToReadFrom.map(key, value) {
             <td>{value}</td>
             <td>{key}</td>
         }}
</tbody>
  • 问题:提示dataToReadFrom为null,页面无法加载。
  1. React State初始化
const [dataToReadFrom, setDataToReadFrom] = useState(userDataA);
  • 问题:用userDataA初始化抛出ReactError 301;留空手动设置则表格无法渲染。

可行解决方案

方案一:React State规范实现

先解决State初始化报错问题(ReactError 301多因初始值非合法可渲染类型,需确保userDataA是已定义的数组),再结合搜索状态切换数据源:

  1. 定义状态
// 确保userDataA、userDataB为格式一致的数组
const [searchQuery, setSearchQuery] = useState('');
const [currentData, setCurrentData] = useState(userDataA);
  1. 处理搜索输入逻辑
const handleSearchChange = (e) => {
  const query = e.target.value.toUpperCase();
  setSearchQuery(query);
  
  // 根据搜索内容切换数据源
  const targetData = query ? userDataB : userDataA;
  
  // 筛选符合条件的数据
  const filteredData = targetData.filter(item => {
    // 替换为实际要搜索的字段,比如item.name
    const txtValue = item.name.toUpperCase();
    return txtValue.indexOf(query) > -1;
  });
  
  setCurrentData(filteredData);
};
  1. 修正表格渲染
<input 
  id="myInput" 
  type="text" 
  onChange={handleSearchChange} 
  placeholder="搜索..." 
/>

<table id="myTable">
  <tr className="header">
    <th style={{width: '60%'}}>Name</th>
    <th style={{width: '40%'}}>Country</th>
  </tr>
  <tbody>
    {currentData.map((item, index) => (
      <tr key={index}>
        <td>{item.name}</td>
        <td>{item.country}</td>
      </tr>
    ))}
  </tbody>
</table>

方案二:直接操作DOM切换数据源

若不想用State管理,可修改原搜索函数,直接重新渲染表格内容:

function myFunction() {
  const input = document.getElementById("myInput");
  const filter = input.value.toUpperCase();
  const table = document.getElementById("myTable");
  const tbody = table.querySelector('tbody');
  
  // 根据搜索内容选择数据源
  const targetData = filter ? userDataB : userDataA;
  
  // 清空现有内容
  tbody.innerHTML = '';
  
  // 渲染筛选后的数据
  targetData.forEach(item => {
    const txtValue = item.name.toUpperCase();
    if (txtValue.indexOf(filter) > -1) {
      const tr = document.createElement('tr');
      tr.innerHTML = `<td>${item.name}</td><td>${item.country}</td>`;
      tbody.appendChild(tr);
    }
  });
}

关键注意事项

  • 确保userDataA和userDataB格式一致,每个元素包含表格对应字段的属性。
  • 原代码map写法错误,React中需用箭头函数(item, index) => (...),且每个列表项需添加唯一key属性。
  • ReactError 301多因userDataA未提前定义或非数组,若数据是异步加载,需增加加载状态判断(比如{userDataA ? ... : <div>加载中</div>})。

内容的提问来源于stack exchange,提问作者DaveCat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 06:37:21