【问题标题】:Get Firestore data before rendering in React在 React 中渲染之前获取 Firestore 数据
【发布时间】:2021-05-11 15:38:10
【问题描述】:

我正在尝试创建一个基本配置文件页面,该页面在包含用户的 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>
      );
    } 
  }

【问题讨论】:

    标签: javascript reactjs asynchronous google-cloud-firestore react-router


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-04-17
      • 2019-08-01
      • 2021-06-01
      • 2019-12-31
      • 2018-09-08
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      相关资源
      最近更新 更多