AsyncAwait在第一次调用时无法在NextJS/ReactFirebase/Firestore上工作
创始人
2024-09-21 02:30:14
0

这个问题通常出现在使用firebase / firestore API进行数据获取的情况下。root cause在于初次加载进入页面时,服务端渲染 (SSR) 使我们的getInitialProps在服务端被调用从而导致我们的异步代码不会执行。因此我们需要在客户端的componentDidMount周期内进行,判断当前页面是在客户端还是服务端,并进行处理在客户端初次渲染时再次拉取数据,而不是仅限服务端。

例如:

import { firebase } from "../lib/firebase";

function HomePage(props) { return (

Home Page
) }

HomePage.getInitialProps = async ({ req }) => { // 如果在服务端,请等待数据完成加载 if (req) { // Create a reference to the cities collection const citiesRef = firebase.firestore.collection('cities'); const snapshot = await citiesRef.get(); const data = snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data })); return { cities: data }; }

return { cities: [] }; };

class HomePageContainer extends React.Component { state = { cities: this.props.cities };

async componentDidMount() { // 如果在客户端,并且没有数据,请等待数据完成加载 if (!this.state.cities.length) { // Create a reference to the cities collection const citiesRef = firebase.firestore.collection('cities'); const snapshot = await citiesRef.get(); const data = snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data })); this.setState({ cities: data }); } }

render() { return ; } }

export default HomePageContainer;

相关内容

热门资讯

科技通报!wpk俱乐部辅助器,... 科技通报!wpk俱乐部辅助器,werplan免费挂下载,好像真的是有挂(有挂细节)1、进入到是否有挂...
揭秘一下!wepoker好友助... 揭秘一下!wepoker好友助力码,wepoker有没有挂,确实是有挂(有挂详情)1、进入游戏-大厅...
今日百科!wepoker私人局... 今日百科!wepoker私人局外卦,wepoker怎么破解游戏,总是是真的有挂(讲解有挂)1、每一步...
关于!hhpoker可以开挂吗... 关于!hhpoker可以开挂吗,约局吧app有挂吗,其实真的是有挂(有挂猫腻)1、在插件功能辅助器技...
玩家必备科普!wepoker怎... 玩家必备科普!wepoker怎么破解游戏,wepoker辅助器免费,确实真的有挂(真的有挂)wepo...
实测必看!pokeplus脚本... 实测必看!pokeplus脚本,hhpoker外挂靠谱吗,其实真的是有挂(有挂总结)1、透视辅助软件...
必看攻略!wpk作弊最怕三个东... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款游戏中打...
免费测试版!德普之星透视辅助,... 免费测试版!德普之星透视辅助,哈糖大菠萝怎么开挂,一直存在有挂(有挂头条)1)辅助插件:进一步探索辅...
专业讨论!约局吧德州真的有透视... 专业讨论!约局吧德州真的有透视挂吗,hhpoker破解工具,果然真的是有挂(有挂技巧)1、实时透视辅...
玩家必看教程!we poker... 玩家必看教程!we poker辅助器下载,hhpoker辅助挂是真的吗,确实真的是有挂(详细教程)1...