问题描述
四处寻找将项目添加到平面列表的正确或最佳方式
Searching around for the correct, or best way to add an item to a flatlist
我的第一个方法是简单地向状态添加一个项目..所以我尝试了这个:
my first approach was to simple add an item to the state.. so I tried this:
var NewObject = {};
NewObject.Name = "New Object";
this.setState({
Data: [...this.state.Data, ...[NewObject]]
});
但是,这样做似乎会导致列表中的所有内容都被读取,并且我会遇到各种关键错误.
However, doing this causes everything in the list to be readded it seems, and i get all sorts of key errors.
是 this.state.Data.push(NewObject);该方法?这似乎不允许重新加载
is this.state.Data.push(NewObject); the approach? that dosen't seem to allow a reload
任何帮助都是巨大的!
推荐答案
可以使用
this.setState({Data: [...this.state.Data, newObject]})
并且在 flatlist 中有一个extraData"道具.使用它来通知 flatlist 其数据源的任何更改.
And there is an 'extraData' prop in flatlist. Use it to notify flatlist about any changes in its datasource.
<FlatList
...
extraData={this.state.Data}
...
>
this.state.Data.push(NewObject) 直接改变状态,永远不要那样做.
this.state.Data.push(NewObject) mutates the state directly, never do that.
P.s 您也可以将 FlatList 的父组件设置为 PureComponent 以获得更好的性能.
P.s You can also set parent component of FlatList as PureComponent for better performance.
这篇关于添加到 FlatList 的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!