问题
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