2017-04-13 71 views
13

与ListView不同,我们可以更新this.state.datasource。有没有更新FlatList或重新渲染它的方法或示例?如何重新呈现flatlist?

我的目标是更新在用户按下按钮...

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} /> 
+3

的[文档的FlatList(https://facebook.github.io/react-native/docs /flatlist.html)说:“这是一个'PureComponent',这意味着如果道具保持浅的平衡,它将不会重新渲染。确保'renderItem'函数所依赖的所有东西都作为不属于'= =='更新后,否则你的用户界面可能无法更新更改,包括'data' prop和父组件状态。你遵循这个建议吗? –

+1

无论我用'extraData'和'shouldItemUpdate'尝试了什么,我都无法获得重新呈现的列表。我最终做的是清除状态,等待它呈现并更新状态。 'this.setState({data:null},()=> {this.setState({data:actualData})});' –

回答

42

在FlatList组件上使用extraData属性。

由于文档状态:

“通过而额外传递= {} this.state到FlatList我们确保FlatList本身将重新呈现在state.selected变化没有设置这个道具,FlatList不知道。它需要重新渲染任何项目,因为它也是一个PureComponent,并且道具比较不会显示任何更改。“

+7

我使用的是redux,在这种情况下,像'data = {this.props.searchBookResults}'发送数据,既没有'extraData = {this.state}'也没有'extraData = {this.props}'正在为我工​​作。而'data = {this.props.searchBookResults}'也不起作用。该怎么办 ? – Sujit

+3

我也在使用REDX并没有工作 –

+0

@EdwinVargas你有没有找到任何解决方案?我不能 – Sujit

2

如果你想有一个按钮,你可以用onPress内的setState更新数据的文本值。然后SetState将重新呈现您的FlatList。

+2

在我的touchablehighlight中有一个setState。 setState工作正常,但flatlist未显示状态值的更新 - > this.state.value – shalonteoh

+0

FlastList中的值未更新,因为您没有直接更新数据源。 this.state。数据是使用FlatList呈现的内容,但在onPress中,您只更新this.state.value。 – WilliamC

+0

对不起,我的错误,问题错字。应该是this.state.data [index] .value – shalonteoh

7

哦,这很简单,只要使用extraData

你看额外的数据在幕后工作的方式是FlatListVirtualisedList只检查通过普通onComponentWillReceiveProps方法wether that object has changed

所以你所要做的就是确保你给extraData改变了一些东西。

这是我做的:

我使用immutable.js所以我要做的就是我传递一个映射(不可变对象),它包含什么我想看。

<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} 
     /> 
    ))} 
/> 

这样一来,当this.props.foothis.props.bar变化,我们CustomComponentRow将更新,因为不可变对象将是一个不同的比以前。

0

我已将FlatList替换为SectionList,它在更改状态时正确更新。

<SectionList 
    keyExtractor={(item) => item.entry.entryId} 
    sections={section} 
    renderItem={this.renderEntries.bind(this)} 
    renderSectionHeader={() => null} 
/> 

唯一需要记住的是,section有差异的结构:

const section = [{ 
    id: 0, 
    data: this.state.data, 
}]