【问题标题】:Object type changed from server to client side in nextjs在 nextjs 中,对象类型从服务器更改为客户端
【发布时间】:2019-11-26 04:13:09
【问题描述】:

在我的 Next.js 应用程序中,我在 getInitialProps 函数中创建一个对象,并在 constructor 中检查该对象的一个​​实例。但是在客户端运行代码时,它的类类型发生了变化。

我的班级是

class TestClass {
    constructor(public name: string, public id: number) {
    }
}

getInitialProps 函数中,我返回了该类的一个对象

static async getInitialProps() {

        const test = new TestType('TestUser', 123);
        return test;
}

在构造函数中检查instanceof 属性时,它在客户端给出了错误的类型。

constructor(props: AppProps) {
        super(props);    
        console.log('test', props.test instanceof TestClass);
        // true on server side but false on client side.
}

所以我的问题是为什么会发生这种情况以及如何在客户端也保持正确的对象类型。

【问题讨论】:

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


    【解决方案1】:

    getInitialProps对其返回的数据进行序列化,函数无法序列化。

    这里提到: https://nextjs.org/docs/api-reference/data-fetching/getInitialProps

    一旦实例作为组件出现在组件上,您就需要对其进行重构。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-03
      • 1970-01-01
      • 2019-09-15
      • 2014-10-08
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 2011-08-24
      相关资源
      最近更新 更多