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

React Native中filter+map调用报错:undefined is not a function

问题分析与解决

你遇到的"undefined is not a function (near '...filteredCars.map')"错误,主要由以下几个问题导致:

1. 拼写错误

你定义的过滤逻辑函数是filteredCars,但在调用map的时候写成了filteredCar(少了末尾的s),导致JS找不到对应的变量,返回undefined,自然无法调用map方法。

2. 过滤函数未返回结果

你的filteredCars函数内部执行了cars.filter(),但没有用return把过滤后的数组返回出去,所以调用这个函数得到的结果是undefined,不是数组,无法调用map。

3. 函数调用方式错误

就算拼写正确,如果你保留函数形式,也需要先执行函数(加括号filteredCars())才能得到过滤后的数组,直接用filteredCars.map是在对函数对象调用map,这显然不对。

另外还有一个潜在的渲染问题:你的汽车数据里图片字段是image,但渲染Card.Cover时用的是item.imagem_principal,这会导致图片加载失败,需要同步字段名。


修正后的代码示例

方式一:直接定义过滤后的数组(推荐,更简洁)

// 直接计算过滤后的数组,不需要包装成函数
const filteredCars = cars.filter((item) => {
  return item.name.toLowerCase().includes(search.toLowerCase());
});

方式二:保留函数形式(适合有更复杂逻辑的场景)

// 确保函数返回过滤后的数组
const filteredCars = () => {
  return cars.filter((item) => {
    return item.name.toLowerCase().includes(search.toLowerCase());
  });
};

修正后的渲染代码

// 注意拼写正确,若用函数形式则需加()调用
const carsItems = filteredCars.map((item) => {
  return (
    <View key={item._id}>
      <View style={{ padding: 10 }}>
        <TouchableOpacity activeOpacity={0.8}>
          <Card
            style={{
              marginLeft: 15,
              marginRight: 15,
              marginTop: 0,
              borderRadius: 10,
            }}
            onPress={() => {
              navigation.push("Details", {
                id: item._id,
                name: item.name,
              });
            }}
          >
            {/* 修正图片字段名 */}
            <Card.Cover
              source={{ uri: item.image }}
              style={{ margin: 5, borderRadius: 10 }}
            />
            <Card.Content>
              <Title>{item.name}</Title>
              <Paragraph>{item.model}</Paragraph>
            </Card.Content>
          </Card>
        </TouchableOpacity>
      </View>
      <Divider />
    </View>
  );
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:40:54