Correct approach to adding to FlatList

末鹿安然 提交于 2019-12-12 19:12:25

问题


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.

is this.state.Data.push(NewObject); the approach? that dosen't seem to allow a reload

any help would be huge!


回答1:


You can use

this.setState({Data: [...this.state.Data, newObject]})

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) mutates the state directly, never do that.

P.s You can also set parent component of FlatList as PureComponent for better performance.



来源:https://stackoverflow.com/questions/48817230/correct-approach-to-adding-to-flatlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!