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

React Native中用useMemo处理renderItem报错不是函数如何解决

问题解决方案

错误根因

  • FlatList的renderItem属性要求传入函数类型值,列表渲染每一项时会自动调用该函数,传入当前项参数后生成对应JSX组件
  • 你当前使用useMemo直接返回了JSX对象,而非函数,因此FlatList尝试调用renderItem(props)时就会抛出「renderItem不是函数」的类型错误

修复写法

你要做性能优化稳定renderItem引用的话,应该用useCallback而非useMemo包裹函数:

import * as React from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Image, Dimensions, FlatList } from 'react-native';
import faker from 'faker';

const { width, height } = Dimensions.get('window');

const Advertising = () => {
  const data = [
    { id: '1', name: 'Jens', image: faker.image.avatar() },
    { id: '2', name: 'Günther', image: faker.image.avatar() }
  ];

  // 用useCallback缓存renderItem函数,稳定引用
  const renderItem = React.useCallback(() => {
    return (
      <View>
        <Text>Hello</Text>
      </View>
    )
  }, [/* 此处填入renderItem内部用到的外部依赖变量,无依赖则留空 */]);

  return (
    <FlatList
      data={data}
      // 修复keyExtractor写法,不要用随机值,会导致组件频繁卸载重挂载,完全抵消性能优化效果
      keyExtractor={item => item.id}
      renderItem={renderItem}
    />
  )
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  }
});

export default React.memo(Advertising);

额外优化提示

你原来的keyExtractor使用Math.random()生成key,会导致每次渲染所有列表项都被强制销毁重新创建,所有性能优化逻辑都会失效,务必使用数据本身的唯一ID作为key。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:54:02