使用 Nextjs 的 getInitialProps 为 firebase DB 设置状态

1nu*_*ter 0 reactjs server-side-rendering next.js

我正在尝试构建 Nextjs 应用程序。我正在使用 GetInitialProps 通过 Firebase 函数执行 SSR。在 getInitialProps 中,我尝试执行 database.ref().child 并将值传递给 UI 。

如何在状态变量中设置更改后的值,以便随时更改 DB 中的值,它会反映在 UI 中。

目前正在返回 getInitialProps 中的值,并且它不反映 DB 值何时发生变化。尽管当我放置控制台记录器时,更改后的值会打印在服务器上。

代码 :

static async getInitialProps({ req,query }) {

    var customer;

    database.ref().child('someKey').child)
    .on('value', function(snapshot) {
        console.log(snapshot.val());
        customer = snapshot.val();
        console.log(customer.name);
        this.setState({waitNum : customer.waitNum});
        return {customer};
    });

    console.log("Hi Here");
    return {customer};
}
Run Code Online (Sandbox Code Playgroud)

Ant*_*iad 5

getInitialProps只执行一次,无论是服务器端(当你第一次下载该网站的页面),或客户端(在您导航到使用另一页Link)。

以下是您应该做的更改:

  1. 更换.on('value', ..).once('value', ..)getInitialProps
  2. 添加.on('value', ..)in componentDidMount,以便您的组件保持更新
  3. 添加一个off()incomponentWillUnmount以在组件卸载时停止侦听。

编辑:

getInitialProps初始化的props,而在componentDidMountstate会集。这可以通过添加一个构造函数来解决,该构造函数将从道具中初始化状态,然后您只能state从渲染中读取状态。

通常被认为是不好的做法,因为现在有不止一个事实来源,并且不清楚当 state 和 props 都发生变化时该怎么办,但在这种特殊情况下我认为这很好,因为它getInitialProps只会运行一次并且如果页面更改组件将被卸载。

另一种选择是getInitialProps完全跳过,特别是如果保留它的唯一原因是减少第一次有意义的显示的时间,因为最终用户可能不会注意到它。通常不值得进行增加代码复杂性的微优化。