如何获取作为对象而不是数组的 Firebase 数据(实时数据库)?

How can I fetch Firebase data (Realtime Database) that is an object, not an array?

我是编码和学习 React Native 和 Firebase 的新手。

我正在尝试使用 Firebase 从 Firebase 实时数据库中获取数据 API。

class UpdatedItem extends React.Component {
  state = {
    loading: false,
    data: [],
    page: 1,
    error: null,
    fullData: []
  }

  componentDidMount() {
    this.makeRemoteRequest()
  }

  makeRemoteRequest = () => {
    const { page } = this.state
    const url = `https://example-default-rtdb.firebaseio.com/dinosaur.json`
    this.setState({ loading: true })

    fetch(url)
      .then(res => res.json())
      .then(res => {
        this.setState({
          data: page === 1 ? [...this.state.data, ...res] : [...this.state.data, ...res],
          error: res.error || null,
          loading: false,
          fullData: res
        })
      })
      .catch(error => {
        this.setState({ error, loading: false })
      })
  }

  render() {
    console.log([...this.state.data])

我成功获取了如下数组的数据。

[ {
  "height" : 2.1,
  "length" : 12.5,
  "name" : "lambeosaurus",
  "weight" : 5000
}, {
  "height" : 4,
  "length" : 9,
  "name" : "stegosaurus",
  "weight" : 2500
} ]

(数组中的数据)

Array [
  Object {
    "height": 2.1,
    "length": 12.5,
    "name": "lambeosaurus",
    "weight": 5000,
  },
  Object {
    "height": 4,
    "length": 9,
    "name": "stegosaurus",
    "weight": 2500,
  },
]

(控制台结果)

但是未能获取对象的数据。

{
  "lambeosaurus" : {
    "height" : 2.1,
    "length" : 12.5,
    "weight" : 5000
  },
  "stegosaurus" : {
    "height" : 4,
    "length" : 9,
    "weight" : 2500
  }
}

(对象中的数据)

Array []

(控制台结果)

我能知道我遗漏了什么以及如何获取对象数据而不是数组数据吗? 提前感谢您的帮助。

这里的区别在于第二个作为对象出现,但您仍在 setState 中使用数组解构:

this.setState({
  data: page === 1 ? [...this.state.data, ...res] : [...this.state.data, ...res],
  ...
})

^ 此模式 ([...array, ...array]) 适用于数组,这就是为什么您在第一个数组中获取数据的原因。但是当数据是一个对象时,你需要一个不同的模式:

this.setState({
  data: page === 1 ? {...this.state.data, ...res} : {...this.state.data, ...res},
  ...
})

^ 注意大括号 - 这是将对象解构为新对象的方式。

现在当您 console.log([...this.state.data]) 时,您不需要再次解构它。如果你只是 console.log(this.state.data),你会看到第一个有一个数组,第二个有一个对象。

最后,因为您分享了这段代码,所以您也应该了解一些关于您的 setState 的一般信息 - 如果您想像这样 更新 状态,使用先前的值作为更新的一部分,您需要像这样从 setState 访问先前的状态 (我将在此处使用目标代码,但也适用于数组或其他任何东西):

this.setState((previousState) => ({
  data: page === 1 ? {...previousState.data, ...res} : {...previousState.data, ...res},
  error: res.error || null,
  loading: false,
  fullData: res
}))