我有一个平面列表,并为平面列表元素创建了一个单独的类。在我显示单位列表的地方,我这样做是这样的:
return (
<View style={styles.container}>
<FlatList
data={this.state.globalPostsArray}
renderItem={renderItem}
keyExtractor={item => item.key}
/>
</View>
)
这很好。我编写的用于渲染平面列表元素renderItem
的函数如下所示:
const renderItem = ({ item }) => (
<FeedCellClass
username={item.username}
description={item.description}
/>
);
feedCellClass
如下所示:
class FeedCellClass extends React.Component{
constructor(props) {
super(props)
this.state = {
username: this.props.params.username,
description: this.props.params.description
}
}
....rest of the class
由于某些原因,出现以下错误:
TypeError: undefined is not an object (evaluating '_this.props.params.username')
这让我觉得我不正确地传递了参数。我该如何解决这个问题?我在网上找到了一些我遵循并已经达到目的的资源,但是没有传递参数。
谢谢
答案 0 :(得分:1)
您正确传递了道具
<FeedCellClass
username={item.username}
description={item.description}
/>
您要传递两个道具的用户名和描述,它们都是字符串,您可以按如下方式访问它。
this.state = {
username: this.props.username,
description: this.props.description
}
因为当您尝试访问未定义道具的username属性时没有称为params的道具,而param会抛出此错误。
如果您像下面那样通过
<FeedCellClass params={{username:"123",description:"456"}}/>
然后您可以像上面一样访问