首页 > 解决方案 > 在 React 中渲染之前获取 Firestore 数据

问题描述

我正在尝试创建一个基本配置文件页面,该页面在包含用户的 Firestore 数据库上运行获取请求,然后返回找到的用户信息。截至目前,我的网页从未加载,可能是因为在我的 get 请求完成之前调用了 render 方法。我可以通过 console.log 语句验证我的 get 请求是否正常工作。从数据库中检索到用户后,如何确保页面更新?谢谢!

class Profile extends Component{

  constructor (props) {
    super(props);
    this.state = {
      uid: 'sampleID',
      user: null,
      isLoaded: false
    };
  }

  componentDidMount () {
    firestore.collection('user').doc(this.state.uid).get()
    .then(res => { 
      this.setState({
        user: res.data(),
        isLoaded: true
        })
      }
    );
  }

    render() {
      return (
        <div>
          {this.state.isLoading ? <h3> Welcome {this.state.user.displayName} </h3> : <h3> Loading </h3>}
        </div>
      );
    } 
  }

标签: javascriptreactjsasynchronousgoogle-cloud-firestorereact-router

解决方案


它不会加载,因为“this.state.isLoading”未定义,它应该是“this.state.isLoaded”

render() {
  return (
    <div>
      {this.state.isLoaded? <h3> Welcome {this.state.user.displayName} </h3> : <h3> Loading </h3>}
    </div>
  );
} 

当请求完成时,它将设置 setState 并再次调用渲染,您的数据将被显示。


推荐阅读