FlatList调用两次

时间:2018-01-20 14:53:46

标签: reactjs react-native

我有这段代码

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 />内的值第一次为空,但第二次是对象。

enter image description here

3 个答案:

答案 0 :(得分:3)

这是正常的RN行为。首先,在创建组件时,您有一个空的DataSource([]),因此FlatList将使用它进行渲染。

之后,componentDidMount会触发并加载更新的数据,这会更新DataSource。

然后,使用setState更新状态,触发重新渲染以更新FlatList。

这里一切正常。如果要尝试,请在构造函数中加载数据源并删除co​​mponentDidMount中的加载。它应该只触发一次。

答案 1 :(得分:2)

如果要控制渲染操作,可以使用shouldComponentUpdate方法。

例如:

shouldComponentUpdate(nextProps, nextState){ if(this.state.friends.length === nextState.friends.lenght) return false; }

如果朋友数不变,它会破坏渲染。

答案 2 :(得分:0)

我在这顿小吃中重现了这个问题。 https://snack.expo.io/B1KoX-EUN-我确认您可以使用shouldComponentUpdate(nextProps,nextState)区分this.state或this.props并返回true / false-https://reactjs.org/docs/react-component.html#shouldcomponentupdate文档说此回调仅应用于优化,这是什么我们在这里。

相关问题