Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - Force ListView Re-render when data has not changed

Is it possible to force a ListView to re-render, even if the data in the dataSource has not changed? I have a ListView within a tab bar in my app and I want it to redraw every time that tab is selected, regardless of if the data is the same or has changed.

this.state = {
  data: props.data,
  dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})
}

componentWillMount() {
  this.setState({
    dataSource: this.state.dataSource.cloneWithRows(nextProps.data)
  })
}

render() {
  <ListView
   dataSource={this.state.data}
   renderRow={this._renderRow}
  />
}

I tried playing with the rowHasChanged arguments but that did not help. Any help would be much appreciated

like image 826
Brien Crean Avatar asked Jun 23 '16 19:06

Brien Crean


1 Answers

So your use-case, as I understand it, is to re-render all rows of ListView because of value changes. I don't know what value is, up to you to determine it, but I will use value to explain my answer:

There are a few ways to solve this. each have pros and cons:

  • easy way: just <ListView key={value} ... /> !! It tells React that ListView needs to get re-render when value changes (it will be unmounted, remounted).
  • "hacky way". replace with a new DataSource. this.setState({ dataSource: new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }).cloneWithData(this.props.data) });
  • the (imo) best practice way: in the data, incorporate value and implements rowHasChanged properly. For instance: (r1, r2) => r1.value !== r2.value && r1.data !== r2.data (<- this is JUST a possible way to represent the data, you have to chose your format, I just assumed you did clone dataSource with nextProps.data.map(data => ({ data, value })).

to me, the third and last solution is the best because:

  • it scales nicely to more condition of re-rendering (other values)
  • it can happen that only part of your rows actually should get re-rendered, and, in that case, you shouldn't re-render all rows for better performance.

here is an other answer I gave on that subject:

What are the exact inputs to rowHasChanged in ListView.DataSource

like image 106
gre Avatar answered Oct 19 '22 15:10

gre