Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

reactjs - FlatList calling twice

I have this code

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;

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.

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is normal RN behavior. At first, when the component is created you have an empty DataSource ([]) so the FlatList is rendered with that.

After that, componentDidMount triggers and loads the updated data, which updates the DataSource.

Then, you update the state with the setState which triggers a re render to update the FlatList.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...