【问题标题】:Set State Using getInitialProps of Nextjs for firebase DB使用 Nextjs 的 getInitialProps 为 firebase DB 设置状态
【发布时间】:2019-03-19 18:35:46
【问题描述】:

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

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

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

代码:

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};
}

【问题讨论】:

    标签: reactjs next.js server-side-rendering


    【解决方案1】:

    getInitialProps 仅在服务器端(当您首次加载网站页面时)或客户端(当您使用 @987654322 导航到另一个页面时)执行一次 @)。

    以下是您应该做的更改:

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

    编辑:

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

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

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

    【讨论】:

    • getInitialProps 中的 .once 现在返回未定义。它适用于 .on 。另外,有没有办法合并 props 和 setState 。 getInitialProps 在使用 componentDidMount 我 setState 时设置道具。展示的时候需要同时展示 state 和 props 吗?
    • 我建议使用.once,因为.on 正在创建订阅,仅使用一次是浪费,但您甚至可以完全跳过getInitialProps,只使用componentDidMount
    猜你喜欢
    • 2018-01-05
    • 2016-06-03
    • 2018-06-19
    • 2019-04-19
    • 1970-01-01
    • 2019-09-01
    • 1970-01-01
    • 2021-09-15
    • 2021-06-23
    相关资源
    最近更新 更多