FlatList 调用两次 [英] FlatList calling twice
问题描述
我有这个代码
class Home extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: []
}
this._handleRenderItem = this._handleRenderItem.bind(this);
this._keyExtractor = this._keyExtractor.bind(this);
}
componentDidMount() {
let success = (response) => {
this.setState({ dataSource: response.data });
};
let error = (err) => {
console.log(err.response);
};
listarProdutos(success, error);
}
_keyExtractor = (item, index) => item._id;
_handleRenderItem = (produto) => {
return (
<ItemAtualizado item={produto.item} />
);
}
render() {
return (
<Container style={styles.container}>
<Content>
<Card>
<CardItem style={{ flexDirection: 'column' }}>
<Text style={{ color: '#323232' }}>Produtos atualizados recentemente</Text>
<View style={{ width: '100%' }}>
<FlatList
showsVerticalScrollIndicator={false}
data={this.state.dataSource}
keyExtractor={this._keyExtractor}
renderItem={this._handleRenderItem}
/>
</View>
</CardItem>
</Card>
</Content>
</Container>
);
}
}
export default Home;
函数 _handleRenderItem()
被调用了两次,我找不到原因.第一次我的 <ItemAtualizado/>
中的值是空的,但第二次是一个对象.
The function _handleRenderItem()
is being called twice and I can't find the reason. The first time the values inside my <ItemAtualizado />
are empty, but the second was an object.
推荐答案
这是 RN 的正常行为.首先,当组件被创建时,你有一个空的 DataSource ([]),所以 FlatList 用它来呈现.
This is normal RN behavior. At first, when the component is created you have an empty DataSource ([]) so the FlatList is rendered with that.
之后,componentDidMount 触发并加载更新的数据,从而更新DataSource.
After that, componentDidMount triggers and loads the updated data, which updates the DataSource.
然后,您使用 setState 更新状态,触发重新渲染以更新 FlatList.
Then, you update the state with the setState which triggers a re render to update the FlatList.
这里一切正常.如果您想尝试,请在构造函数中加载数据源并删除 componentDidMount 中的加载.它应该只触发一次.
All normal here. If you want to try, load the datasource in the constructor and remove the loading in the componentDidMount. It should only trigger once.
这篇关于FlatList 调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!