react原生usememo renderitem不工作为什么?

y1aodyip  于 2022-11-25  发布在  React
关注(0)|答案(2)|浏览(127)

我想避免不必要的重新呈现,所以我使用useMemo。
但我收到了以下错误消息:

TypeError: renderItem is not a function. (In 'renderItem(props)', 'renderItem' is an instance of Object)

编码:

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() }
  ];

  const renderItem = React.useMemo(() => {
    return (
      <View>
        <Text>Hello</Text>
      </View>
    )
  }, [data]);

  return (
    <FlatList
      data={data}
      keyExtractor={item => Math.random(100).toString()}
      renderItem={renderItem}
    />
  )
};

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

export default React.memo(Advertising);

......................................................................................................................................................................................................

vuktfyat

vuktfyat1#

useMemo是一个react钩子,不能以那种方式使用react钩子。
我建议您为this创建一个单独的组件。

const MyComponent = React.memo(({item})=>{
   return (<View></View>);
});

然后像这样导入

const renderItem = ({item}) => {
  return <MyComponent />
}
...
<FlatList 
data={data}
renderItem={renderItem}
keyExtractor={(_item, i)=>i.toString()}
/>

还可以考虑使用CallBack

scyqe7ek

scyqe7ek2#

您必须在useMemo内将renderItem函数作为回调返回。

const renderItem = React.useMemo(() => () => (
  <View>
    <Text>Hello</Text>
  </View>
), [data])

与...相同

const renderItem = () => (
  <View>
    <Text>Hello</Text>
  </View>
)

const memoizedRenderItem = React.useMemo(renderItem, [data])

相关问题