简体   繁体   English

如何从React / Firebase中的Promise中获取数据?

[英]How to get data out of a Promise in React/Firebase?

This is the promise within a render() method of a React component. 这是React组件的render()方法中的承诺。

firebaseRef.child("users/" + auth.uid).once('value').then((snapshot) => {
   let userName = snapshot.val().name;
});

I want to get the data of snapshot.val().name and put it in the 我想获取snapshot.val()。name的数据并将其放在

return(
    <h1>{userName}</h1>
)

I could get the data out of the promise with an action dispatch to the redux store and then retrieving it where I need it but there should be a shorter way of achieving it I suppose? 我可以通过将动作分派到redux存储来从promise中获取数据,然后在需要的地方检索它,但是我想应该有一种更短的方法来实现它吗? I tried different ways to do so but I failed due to the asynchronicity so... please help! 我尝试了不同的方法来执行此操作,但由于异步性而失败了,所以请...帮助!

I haven't done React in a while, but I think it's: 我有一段时间没有做React了,但我认为是:

firebaseRef.child("users/" + auth.uid).once('value').then((snapshot) => {
   let userName = snapshot.val().name;
   this.setState({ userName: userName });
});

I was going to upvote the previous comment, but he failed to mention that doing this inside of the render method is a bad idea. 我本来要反对前面的评论,但他没有提到在render方法中执行此操作是一个坏主意。 That would make an infinite loop. 那将造成无限循环。 Render -> promise resolves -> set state -> render -> repeat. 渲染->承诺解析->设置状态->渲染->重复。 You should do your firebase promise like this: 您应该像这样履行您的firebase承诺:

class Test extends React.Component{
  constructor() {
    super()
    this.state = {}
  }

  componentDidMount() {
    let { auth } = this.props //or wherever it comes from

    firebaseRef.child("users/" + auth.uid).once('value').then((snapshot) => {
      this.setState({ userName: snapshot.val().name });
   });
  }

  render() { 
    let { userName } = this.state
    return (
      <h1>{userName}</h1>
    )
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM