How to re-render flatlist?
Unlike ListView we can update this.state.datasource. Is there any method or example to update FlatList or re-render it?
My goal is to update the text value when user press button ...
renderEntries({ item, index }) {
return(
<TouchableHighlight onPress={()=> this.setState({value: this.state.data[index].value+1})>
<Text>{this.state.data[index].value}</Text>
</TouchableHighlight>
)
}
<FlatList
ref={(ref) => { this.list = ref; }}
keyExtractor={(item) => item.entry.entryId}
data={this.state.data}
renderItem={this.renderEntries.bind(this)}
horizontal={false} />
Solution 1:
Use the extraData
property on your FlatList component.
As the documentation states:
By passing
extraData={this.state}
toFlatList
we make sureFlatList
will re-render itself when thestate.selected
changes. Without setting this prop,FlatList
would not know it needs to re-render any items because it is also aPureComponent
and the prop comparison will not show any changes.
Solution 2:
For quick and simple solution Try:
-
set extra data to a boolean value.
extraData={this.state.refresh}
-
Toggle the value of boolean state when you want to re-render/refresh list
this.setState({ refresh: !this.state.refresh })
Solution 3:
Oh that's easy, just use extraData
You see the way extra data works behind the scenes is the FlatList or the VirtualisedList just checks wether that object has changed via a normal onComponentWillReceiveProps
method.
So all you have to do is make sure you give something that changes to the extraData
.
Here's what I do:
I'm using immutable.js so all I do is I pass a Map (immutable object) that contains whatever I want to watch.
<FlatList
data={this.state.calendarMonths}
extraData={Map({
foo: this.props.foo,
bar: this.props.bar
})}
renderItem={({ item })=>((
<CustomComponentRow
item={item}
foo={this.props.foo}
bar={this.props.bar}
/>
))}
/>
In that way, when this.props.foo
or this.props.bar
change, our CustomComponentRow
will update, because the immutable object will be a different one than the previous.
Solution 4:
OK.I just found out that if we want the FlatList to know the data change outside of the data prop,we need set it to extraData, so I do it like this now:
<FlatList data={...} extraData={this.state} .../>
refer to : https://facebook.github.io/react-native/docs/flatlist#extradata
Solution 5:
If you are going to have a Button, you can update the data with a setState inside the onPress. SetState will then re-render your FlatList.