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

React中如何通过多选框过滤并展示companies数组?

问题分析与解决方案

核心问题

你错误地将过滤后的结果覆盖了原始的companies状态,导致后续过滤操作只能基于上一次的过滤结果,而非完整的原始数据。比如第一次过滤后,companies变成了符合条件的子集,下次再过滤时就只能从这个子集里筛选,自然无法得到正确结果。

修复步骤

  1. 保留原始数据:将原始的公司数据单独存储(用常量或独立状态),确保过滤操作始终基于完整的数据源。
  2. 动态计算过滤结果:不在状态中存储过滤后的数组,而是在渲染时根据当前filters动态计算需要展示的公司列表。
  3. 简化逻辑:只维护filters状态,移除不必要的companies状态更新操作。

修改后的完整代码

function App() {
  // 原始公司数据,作为常量存储,不修改
  const originalCompanies = [
    { id: 1, status: "accepted", name: "001", date: "01/01/2022" },
    { id: 2, status: "accepted", name: "001", date: "01/01/2022" },
    { id: 8, status: "accepted", name: "001", date: "10/04/2022" },
    { id: 3, status: "pending", name: "002", date: "02/02/2022" },
    { id: 4, status: "declined", name: "003", date: "03/03/2022" }
  ];

  const [filters, setFilters] = useState([]);

  // 动态计算过滤后的公司列表
  const filteredCompanies = filters.length === 0
    ? originalCompanies // 无选中过滤器时展示全部
    : originalCompanies.filter(company => filters.includes(company.status));

  const handleFilters = (data) => {
    setFilters(data);
  }

  return (
    <div className="App">
      <Checkbox 
        handleFilters={handleFilters}
      />

      {/* 公司列表 */}
      <div>
        {filteredCompanies.length ? 
          (
            <table>
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Estado</th>
                  <th>nombre</th>
                  <th>Fecha</th>
                </tr>
              </thead>
              <tbody>
                {filteredCompanies.map((company) => (
                    <tr key={company.id}> {/* 用唯一id作为key,避免索引带来的渲染异常 */}
                      <td>{company.id}</td>
                      <td>{company.status}</td>
                      <td>{company.name}</td>
                      <td>{company.date}</td>
                    </tr>
                  )
                )}
              </tbody>
            </table>   
          ) : (
            <h2>No hay compañías para mostrar</h2>
          )
        }
      </div>

      {/* 列表数量 */}
      <div>
          <h3>Cantidad de compañías: {filteredCompanies.length}</h3>
      </div>
    </div>
  );
}

export default App;

额外优化点

  • 使用公司的id作为map的key,而非索引,符合React最佳实践,避免渲染异常。
  • 增加空过滤器判断:未选中任何状态时默认展示所有公司,可根据需求调整该逻辑。

内容的提问来源于stack exchange,提问作者Ignacio García

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:25:20