我有一个像这样的异步函数:
getDeals() {
if(this.props.user) {
this.setState({loading: true});
this.setState({deals: []});
var parameters = {
zip: this.props.user.zip,
sort: 'All',
category: this.props.selectedCategory,
company: this.props.user.company,
page: null,
user: this.props.user,
search: null
}
axios.post(`${constants.api}/grab-deals/`, parameters)
.then((response) => {
this.setState({totalDeals: response.data.length});
this.setState({deals: response.data, loading: false, refreshing: false});
this.forceUpdate();
})
}
}
和FlatList组件像这样:
<FlatList data={this.state.deals} style={{flex: 1, padding: 10}} extraData={this.state} keyExtractor={this.keyExtractor} renderItem={this.renderDeal.bind(this)} />
这是keyextractor:keyExtractor = (item, index) => item.id;
当我第一次打电话给this.getDeals()
时它很棒。然而,当我第二次调用它时,axios调用得到所有正确的数据,但是平面列表仍然保留旧数据(它不会删除不在新调用中的项目)。
如何让FlatList始终反映返回的数据?
在this.getDeals()
中调用componentWillUpdate()
并更新道具?
我相信你会混淆道具和国家的含义。基本上,状态用于在组件的生命周期中可能发生变化的事物,并且道具保持不变。我用它们来表现。
除非您在第二次调用时更改getDeals函数的参数,否则请参阅所有属性都基于道具,而道具并不总是更新。
RN有一个名为componentWillUpdate的方法,该方法由新的道具触发,然后您可以使用它来更新组件本身。如果你想在你的getDeals方法中继续使用道具,你将需要检查道具是否已经改变(当父亲用新道具更新孩子时会发生这种情况),然后再次触发数据提取。
如果这没有帮助,请发布更多代码。
根据docs你需要设置state.selected
值
通过将extraData = {this.state}传递给FlatList,我们确保当state.selected更改时,FlatList本身将重新呈现。如果不设置此prop,FlatList将不知道它需要重新渲染任何项目,因为它也是PureComponent,并且prop比较不会显示任何更改。