尝试使用 reactjs 在 firebase 中拥有唯一的数字 ID

Trying to have a unique number ID in firebase, using reactjs

我似乎无法将计数器值设置为最后插入的查询的 ID。好像是空的?

componentDidMount() {
//Last inserted query
let postRef = firebase.database().ref('clients').orderByKey().limitToLast(1); 
//Fetch the data from the query
postRef.on('value', snapshot => {

  this.setState({ counter: snapshot.child('clients').child('ID').val()});

});


}

这应该可以解决问题:

let postRef = firebase.database().ref('clients').orderByKey().limitToLast(1); 
postRef.once('child_added', snapshot => {
  this.setState({ counter: snapshot.child('ID').val()});
});

我对您的代码所做的更改:

  • 现在使用 once 而不是 on,因为我假设您不打算获得连续更新。如果您确实希望接收更新,因为密钥是 added/removed,请使用 on.
  • 我监听 child_added 因为它会触发正确的 child 节点。如果您监听 value,则需要循环快照(使用 snapshot.forEach() 到达 child 节点。
  • 我从您的代码中删除了 child('clients'),因为每个 child 下没有 clients 节点。