簡體   English   中英

React Native-無法獲取數組中的項目,或無法從列表中顯示數組中的項目

[英]React Native - Cannot get item in array, or show items from array in list

我已經嘗試調試了幾個小時,但無濟於事。 我寫的腳本基本上是在組件加載時從Firestore數據庫中獲取信息的。 然后,我將陣列中的一項記錄到控制台,結果為undefined 我不明白為什么它可以顯示完整的陣列而不顯示一個項目。 然后整個數組生成完整數組(部分圖像如下所示)。

在此處輸入圖片說明

該組件的主要目標是生成一個項目列表,如列表組件所示,但未顯示任何內容。 我的第一個猜測是從數據庫獲取信息的方法是異步的,但是如果狀態更新了,這會很重要嗎? 該應用程序是否應該重新渲染?

這是我的代碼的片段,非常感謝您的幫助!

export default class ItemScreen extends Component {

  constructor () {
    super()
    this.state = {
      items: [],
    }
  }

  componentDidMount() {
    var items = []
    firebase.firestore().collection("items").get().then(function(querySnapshot) {
      querySnapshot.forEach(function(doc) {
          items.push(doc.data());
      });
    })
    this.setState({items: items});
    console.log(items[1])
    console.log(items)
  }

  render() {
    const { items } = this.state
    return (
        <View style={styles.container}>
          <SearchBar
            lightTheme
            onChangeText={(text) => console.log(text)}
            onClearText={() => console.log("cleared")}
            placeholder='Type Here...' 
            containerStyle={{width: "100%"}}
          />
          <List containerStyle={{width: "100%"}}>
            {
              items.map((l) => (
                <ListItem
                  roundAvatar
                  avatar={{uri:l.image}}
                  key={l.name}
                  title={l.name}
                />
              ))
            }
          </List>
        </View>
    );
  }
}

嘗試重組為更類似的內容

var items = []
var self = this;
firebase.firestore().collection("items").get().then(function(querySnapshot) {
  querySnapshot.forEach(function(doc) {
      items.push(doc.data());
  });
  self.setState({items: items});
  console.log(items[1])
  console.log(items)
})

原始方法底部的代碼將在結果可用之前運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM