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;

相关内容

热门资讯

揭秘关于!哈糖大菠萝开挂(辅助... 揭秘关于!哈糖大菠萝开挂(辅助挂)总是是真的有挂(有挂方法)1、首先打开哈糖大菠萝开挂辅助器下载最新...
必看攻略!德普之星透视辅助软件... 必看攻略!德普之星透视辅助软件下载(辅助挂)都是存在有挂(真的有挂)运德普之星透视辅助软件下载辅助工...
玩家必知教程!wepoker怎... 玩家必知教程!wepoker怎么看牌型(辅助挂)其实有挂(有挂教程)1、金币登录送、破产送、升级送、...
我来分享!约局吧能不能开挂(辅... 我来分享!约局吧能不能开挂(辅助挂)总是真的是有挂(有挂透视)亲,关键说明,约局吧能不能开挂透视脚本...
技术分享!wepoker免费脚... 技术分享!wepoker免费脚本咨询(辅助挂)竟然真的是有挂(有挂攻略)一、wepoker免费脚本咨...
重大通报!wepoker免费钻... 重大通报!wepoker免费钻石(辅助挂)切实有挂(真的有挂)1、全新机制【wepoker免费钻石a...
实测揭晓!wepoker怎么设... 实测揭晓!wepoker怎么设置房间(辅助挂)本来有挂(有挂规律)1、点击下载安装,wepoker怎...
盘点一款!wepoker透视器... 盘点一款!wepoker透视器免费(辅助挂)其实真的有挂(有挂秘笈)亲,关键说明,wepoker透视...
重大通报!德州局hhpoker... 重大通报!德州局hhpoker(辅助挂)确实有挂(有挂方式)1、许多玩家不知道德州局hhpoker辅...
带你了解!sohoo辅助(辅助... 带你了解!sohoo辅助(辅助挂)一直有挂(有挂神器)1)sohoo辅助辅助插件:进一步探索soho...