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;

相关内容

热门资讯

开挂透视!werplan透视挂... 开挂透视!werplan透视挂!果然存在有辅助攻略(有挂详细)-哔哩哔哩;1)werplan透视挂辅...
曝光透视!wepoker有辅助... 曝光透视!wepoker有辅助插件吗,wepoker钻石怎么看底牌,指引教程(有挂教学)-哔哩哔哩1...
揭露透视!newpoker怎么... 揭露透视!newpoker怎么安装脚本!切实存在有辅助方法(有挂透明挂)-哔哩哔哩1、完成newpo...
解密透视!wepoker怎么挂... 解密透视!wepoker怎么挂飞机,wpk真吗,攻略教程(有挂头条)-哔哩哔哩1、wepoker怎么...
曝光透视!pokeplus脚本... 曝光透视!pokeplus脚本!一贯有辅助教程(有挂解密)-哔哩哔哩1、用户打开应用后不用登录就可以...
解迷透视!wepoker买脚本... 解迷透视!wepoker买脚本靠谱吗,wepoker透视底牌,方针教程(有挂工具)-哔哩哔哩1、用户...
分享透视!pokerrrr2辅... 分享透视!pokerrrr2辅助!总是真的有辅助技巧(有挂秘笈)-哔哩哔哩1、在pokerrrr2辅...
揭幕透视!we poker游戏... 揭幕透视!we poker游戏下,aapoker透视怎么用,窍要教程(有挂助手)-哔哩哔哩揭幕透视!...
专业透视!pokemmo辅助器... 专业透视!pokemmo辅助器!本来有辅助app(有挂秘笈)-哔哩哔哩1)pokemmo辅助器有没有...
揭露透视!拱趴大菠萝辅助神器,... 揭露透视!拱趴大菠萝辅助神器,aapoker破解侠是真的吗,大纲教程(有挂秘籍)-哔哩哔哩1、aap...