javascript - React Native - 无法获取数组中的项目,或无法在列表中显示数组中的项目

标签 javascript firebase react-native google-cloud-firestore

我已经尝试调试了几个小时,但无济于事。我写了这个脚本,基本上当组件加载时从我的 Firestore 数据库中获取信息。然后,我将数组中的一项记录到控制台,结果为 undefined。我不明白为什么它可以显示完整的数组而不是一个项目。然后整个阵列产生完整阵列(见下图的部分图像)。

enter image description here

此组件的主要目标是生成列表组件中所见但未显示任何内容的项目列表。我的第一个猜测是从数据库中获取信息的方法是异步的,但是如果更新了状态,这会很重要吗?应用程序不应该重新渲染吗?

这是我的代码片段,非常感谢您的帮助!

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)
})

原始方法底部的代码会在结果可用之前运行。

关于javascript - React Native - 无法获取数组中的项目,或无法在列表中显示数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52435240/

相关文章:

javascript - 将用户数据从一个屏幕传递到另一个屏幕 - React Native

javascript - 一个页面上的多个页面

javascript - 在双下拉选择选项中选择选项时显示输入文本

firebase - 使用 Firebase signInWithRedirect 是否可以将其配置为将我重定向回特定页面

android - 在 React native 应用程序上获得 'One of the sources for assign has an enumerable key on the prototype chain'

react-native - wix react 原生导航 v2 |如何从侧边抽屉组件将新屏幕推送到当前屏幕

react-native - react native 雪碧表

javascript - 在 AngularJS 中表中添加的行上显示弹出窗口 3 秒

javascript - 在<li>中放置onClick事件来调用AJAX

javascript - 火存储 : Dynamically Update Document (web)