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

React.js中localtypes过滤返回空数组及props访问问题求助

问题分析与解决方案

1. 修复Props传递错误

你当前传递categories props的方式存在问题:

categories={() => type()}

这种写法相当于传递了一个新函数,该函数内部调用type()时没有传递任何参数,所以当你在Filter组件中调用categories("farmacia")时,type函数里的category参数会是undefined,自然过滤不到匹配项,返回空数组。

正确的传递方式是直接把type函数作为props传递:

categories={type}

这样在Filter组件中调用categories("farmacia")时,参数就能正确传递给type函数。

2. 保留原始数据,避免过滤后数据丢失

另一个隐藏问题:你每次过滤都直接基于当前的restaurants状态克隆数组,第一次过滤后,restaurants会变成过滤后的子集,后续再过滤时就只能在这个子集里查找,无法回到原始数据重新过滤。

解决方法是保存一份原始的API数据,过滤始终基于原始数据:

// 初始化两个状态:原始数据和用于展示的过滤后数据
const [originalRestaurants, setOriginalRestaurants] = useState([]);
const [restaurants, setRestaurants] = useState([]);

// 获取API数据时,同时设置原始数据和展示数据
useEffect(() => {
  fetch('你的API地址')
    .then(res => res.json())
    .then(data => {
      setOriginalRestaurants(data);
      setRestaurants(data);
    });
}, []);

// 修改过滤函数,基于原始数据处理
const type = (category) => {
  const filtered = originalRestaurants.filter(restaurant => {
    // 建议用严格相等===,避免类型隐式转换问题
    return restaurant.localtype === category;
  });
  setRestaurants(filtered);
};

3. 验证数据匹配一致性

另外要确认API返回的localtype字段值是否和你传入的"farmacia"完全一致(包括大小写、拼写),比如如果API返回的是"Farmacia"首字母大写,用===匹配就会失败,这时候可以统一转成小写再比较:

return restaurant.localtype.toLowerCase() === category.toLowerCase();

内容的提问来源于stack exchange,提问作者Arturo Suárez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:35:21