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;

相关内容

热门资讯

第八分钟辅助!wepoker透... 第八分钟辅助!wepoker透视底牌脚本,德普之星怎么设置埋牌,手段教程(有挂教学)1、全新机制【德...
第3分钟辅助!wepoker透... 第3分钟辅助!wepoker透视最简单三个步骤,wepokerplus作弊,绝活教程(有挂详情)运w...
九分钟辅助!steampoke... 九分钟辅助!steampokermaster辅助,wpk作弊是真的吗,妙计教程(有挂教程)1、ste...
7分钟辅助!wepokerpl... 7分钟辅助!wepokerplus外挂,wepoker开辅助能查到吗,方式教程(的确有挂)1、全新机...
第九分钟辅助!wepoker辅... 第九分钟辅助!wepoker辅助软件视频,wpk透视是真的吗,窍要教程(有挂透明挂)1、游戏颠覆性的...
4分钟辅助!wepoker俱乐... 4分钟辅助!wepoker俱乐部辅助器,wepoker线上大神,手筋教程(有挂详细)一、wepoke...
3分钟辅助!xpoker辅助控... 3分钟辅助!xpoker辅助控制,wepoker破解器激活码,绝活儿教程(有挂秘诀)在进入wepok...
1分钟辅助!pokemmo手机... 1分钟辅助!pokemmo手机辅助软件,pokerworld辅助器,练习教程(有挂攻略)1、玩家可以...
第7分钟辅助!德普之星的辅助工... 第7分钟辅助!德普之星的辅助工具介绍,wepoker破解器,机巧教程(有挂猫腻)1、操作简单,无需德...
第七分钟辅助!wpk俱乐部辅助... 第七分钟辅助!wpk俱乐部辅助器,竞技联盟辅助,方式教程(有挂细节)一、wpk俱乐部辅助器可以开透视...