无法更改平面列表renderItem中的道具

时间:2019-11-04 08:22:13

标签: react-native react-native-flatlist

我正在尝试使用两种方式呈现数组数据:普通视图 FlatList 。我了解到的是,我们在 map renderItem 中传递了props

第一个块给出正确的输出:

const DATA = [
    {id: '1',title: 'First Item'},
    {id: '2',title: 'Second Item'},
]

const list = DATA.map((lst)=>{
    return(<Text key={lst.id}>{lst.title}</Text>)
})

const Home=()=>{
  return (<View><Text>{list}</Text></View>)
}
export default Home

在以下FlatList组件中,它引发错误:

TypeError:TypeError:undefined is not an object(evaluating 'lst.title')

如果我将lst更改为Item,则显示正确的输出。 item是renderItem中的预定义关键字吗?如果我将item更改为其他任何单词,则会引发错误。

const DATA = [
    {id: '1',title: 'First Item'},
    {id: '2',title: 'Second Item'},
] 
const Itm=({title})=>{
  return (
    <View>
      <Text>{title}</Text>
    </View>
  );
}

const Home=()=>{
  return (
      <FlatList
        data={DATA}
        renderItem={({lst}) => <Itm title={lst.title} />}
        keyExtractor={itm => itm.id}
      />
  );
}
export default Home

2 个答案:

答案 0 :(得分:0)

问题在于,在renderItem中,您正在读取lst关键字来破坏对象:

renderItem={({lst}) => <Itm title={lst.title} />} //Wrong

您正在尝试在没有该键的对象中读取属性lst

({lst})更改为(lst)

renderItem={(lst) => <Itm title={lst.title} />}

您可以在以下内容中了解有关对象分解的信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring

编辑。

看着FlatList react-native DocsFlatlist返回的对象看起来像:

{item, index, separators}

item是您需要呈现的项目。

所以您需要使用:

renderItem={({item }) => <Itm title={lst.title} />} //must be item

renderItem={({item: lst}) => <Itm title={lst.title} />}

答案 1 :(得分:0)

尝试删除{}

renderItem={({lst}) => <Itm title={lst.title} />}

它不需要写出知道它是析构函数的对象,而是尝试使用这种形状

    renderItem={(lst) => <Itm title={lst.title} />}
相关问题