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

React数据映射报错:Cannot read properties of undefined (reading 'filter')

解决React数据映射报错:Cannot read properties of undefined (reading 'filter')

问题根源

报错是因为filters.list为undefined时调用了filter方法。API新增count和list字段后,数据结构从数组变成了包含list数组的对象,但你的初始状态设置错误,且数据加载过程中未处理好空值情况。

修复步骤

  1. 修正初始状态
    原代码中filters初始值为空数组,而现在API返回的是包含list的对象,需要将初始状态改为包含空list的对象:

    const [data, setData] = useState({ list: [] });
    const [filters, setFilters] = useState({ list: [] });
    
  2. 优化数据获取逻辑

    • 用useRef跟踪组件挂载状态(原代码中componentMounted未定义,会导致bug)
    • 无需重复调用response.json(),一次解析即可复用结果
    import { useState, useEffect, useRef } from 'react';
    
    // ...
    
    const componentMounted = useRef(true);
    
    useEffect(() => {
      const getProduct = async () => {
        try {
          const response = await fetch('你的数据源');
          if (!response.ok) throw new Error('请求失败');
          const result = await response.json();
          if (componentMounted.current) {
            setData(result);
            setFilters(result);
          }
        } catch (err) {
          console.error('获取数据出错:', err);
        }
      };
      getProduct();
      return () => {
        componentMounted.current = false;
      };
    }, []);
    
  3. 增强映射代码的容错性
    即使filters.list意外为undefined,也提供默认空数组避免报错:

    {(filters?.list || []).filter((product) => product.id === id).map((product) => (
      <div className='product-bigger-wrapper' key={product.id}>
        <div className="product-list-wrapper"> 
          <div className="product-detail-container">               
            <div>                    
              <div className="image-container">
                <img src={product.image} className="product-detail-image" alt={product.name || '产品图片'}/>
              </div>            
            </div>
            {/* 其他组件内容 */}
          </div>
        </div>
      </div>
    ))}
    

    注意:给映射的元素加上唯一key属性,符合React最佳实践。

额外检查

  • 确认API返回的数据结构确实包含list字段,且list是数组类型
  • 若API可能返回list为null,则上述(filters?.list || [])的写法能覆盖这种情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:48:30