首页 > 解决方案 > 在 nextjs 中,对象类型从服务器更改为客户端

问题描述

在我的 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.
}

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

标签: reactjsserver-sidenext.jsserver-side-rendering

解决方案


getInitialProps序列化它返回的数据,函数不能序列化。

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

一旦实例作为组件的道具出现,您就需要重建实例。


推荐阅读