【问题标题】:React Native - Cannot get item in array, or show items from array in listReact Native - 无法获取数组中的项目,或在列表中显示数组中的项目
【发布时间】:2019-02-25 08:42:12
【问题描述】:

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

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

这是我的代码的 sn-p,非常感谢您的帮助!

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

【问题讨论】:

  • 你有一个 Promise .get().then(,记住在 JS 中你没有 I/O 阻塞,这意味着当你使用 Promise 时异步执行代码,只将日志关闭发送到 then
  • 当 IO 尝试这样的事情时,我收到一个错误,即 this.state 不是函数。见下文

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


【解决方案1】:

尝试重组为类似的东西

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

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

【讨论】:

  • 当使用该结构时,我收到以下错误:Possible Unhandled Promise Rejection (id: 0): TypeError: this.setState is not a function
  • 试试我更新的代码...闭包搞乱了“this”的范围。
  • @kip haha​​ 太真实了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-19
  • 2022-01-09
  • 2014-11-10
  • 2013-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多