如何在React Native中更新FlatList中的单个项目?
问题描述:
假设我正在写一个Twitter的克隆,但是要简单得多。我把每个项目放在FlatList中并渲染它们。如何在React Native中更新FlatList中的单个项目?
要“喜欢”一篇文章,我按下帖子上的“喜欢”按钮,“喜欢”按钮变成红色,我再次按下,它变成灰色。
这是我到目前为止:我将所有加载的帖子存储在this.state
中,每个帖子都有一个名为“likes”的属性,它是布尔值,表示此用户是否喜欢此帖子,当用户按下“像”,我去state.posts
和更新后的liked
属性,然后用this.setState
更新的帖子,像这样:
// 1. FlatList
<FlatList
...
data={this.state.posts}
renderItem={this.renderPost}
...
/>
// 2. renderPost
renderPost({ item, index }) {
return (
<View style={someStyle}>
... // display other properties of the post
// Then display the "like" button
<Icon
name='favorite'
size={25}
color={item.liked ? 'red' : 'gray'}
containerStyle={someStyle}
iconStyle={someStyle}
onPress={() => this.onLikePost({ item, index })}
/>
...
</View>
);
}
// 3. onLikePost
likePost({ item, index }) {
let { posts } = this.state;
let targetPost = posts[index];
// Flip the 'liked' property of the targetPost
targetPost.liked = !targetPost.liked;
// Then update targetPost in 'posts'
posts[index] = targetPost;
// Then reset the 'state.posts' property
this.setState({ posts });
}
这种方法的工作原理,但是,实在是太慢了。 “按钮”按钮的颜色随着按压而翻转,但颜色变化前通常需要1秒左右的时间。我想要的是,当我按下它时,颜色几乎会在同一时间翻转。
我知道为什么会发生这种情况,我可能不会使用this.setState
,但我还可以尝试其他方法吗?
答
如果您在android上测试,请尝试关闭开发者模式。还是你打了一些API并更新服务器上的帖子,并更新UI中对应于服务器响应的按钮?如果是这样的话,请告诉我,我也遇到过这个,我解决了它。此外,我还评论了代码中不需要的第二行。
// 1. FlatList
<FlatList
...
data={this.state.posts}
renderItem={this.renderPost}
...
/>
// 2. renderPost
renderPost({ item, index }) {
return (
<View style={someStyle}>
... // display other properties of the post
// Then display the "like" button
<Icon
name='favorite'
size={25}
color={item.liked ? 'red' : 'gray'}
containerStyle={someStyle}
iconStyle={someStyle}
onPress={() => this.onLikePost({ item, index })}
/>
...
</View>
);
}
// 3. onLikePost
likePost({ item, index }) {
let { posts } = this.state;
let targetPost = posts[index];
// Flip the 'liked' property of the targetPost
targetPost.liked = !targetPost.liked;
// Then update targetPost in 'posts'
// You probably don't need the following line.
// posts[index] = targetPost;
// Then reset the 'state.posts' property
this.setState({ posts });
}
谢谢你的回复。我没有听到服务器更改。我在后台更新数据库中的'喜欢'属性,但我知道这需要一些时间,因此,我必须给用户一个即时反馈,这就是为什么我更新该帖子的'喜欢'属性并使用' this.setState'首先在本地更改帖子。实际上,在'this.setState({posts})'这行之后,我继续更新数据库中的记录,我忘了在我的问题中写下这个记录,对此抱歉。我不知道为什么需要大约1秒来更新帖子 –
如果您在数据库操作之前正在执行setState,那么它应该快速执行。你能粘贴一些涉及的更多代码吗? –
你是对的,我试图在setState之前修改数据库,我认为这是一个异步操作,所以先做哪个操作并不重要。现在颜色几乎立即改变 –