简体   繁体   English

如果数据已更新,如何更新FlatList

[英]How to update FlatList if data is updated

The way I get the data is inside the componentWillMount method, its working fine when it renders the FlatList when the app boots up, but when I'm adding data, all I want is to update also my flatList. 我获取数据的方式是在componentWillMount方法内部,当应用启动时,它在呈现FlatList时可以正常工作,但是当我添加数据时,我想要的也就是更新我的flatList。 How can I do that here's the code snippet: 我该怎么做,这是代码片段:

 componentWillMount() {
    console.log(`componentDidUpdate`, prevProps);
    const user = firebase.auth().currentUser;

    if (user != null) {
      const db = firebase.firestore();
      const docRef = db.collection('userCheckInHistory').doc(user.uid);
      docRef
        .get()
        .then(doc => {
          if (doc.exists) {
            let shopId = this.props.shopId;
            let userShopHistoryData = doc.data();
            let userShopPick = userShopHistoryData[shopId];
              this.setState({
                checkInHistory: userShopPick,
                shopId: this.props.shopId
              });


          } else {
            console.log('No such document!');
            return false;
          }
        })
        .catch(function(error) {
          console.log('Error getting document:', error);
        });
    }
  }

Now this is my FlatList code: 现在,这是我的FlatList代码:

renderHistoryList() {
    const sortedData = Common.getArrayByObject(this.state.checkInHistory);
    if (this.state.checkInHistory !== '') {
      return (
        <FlatList
          data={sortedData}
          extraData={this.state}
          keyExtractor={this._keyExtractor}
          renderItem={({ item }) => (
            <MyListItem
              id={item}
              onPressItem={this._onPressItem}
              selected={!!this.state.selected.get(item)}
              title={item}
            />
          )}
        />
      );
    } else {
      return <Spinner />;
    }
  }

When you get your data from api set your state with that data. 从api获取数据时,请使用该数据设置状态。 And then if you add data and setState, react native will rerender app and you will see your data on the list. 然后,如果您添加数据和setState,则react native将重新渲染应用程序,您将在列表中看到数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM