在nextjs中,对象类型从服务器端改为客户端。

问题描述 投票:2回答:1

在我的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个回答
0
投票

getInitialProps 将从中返回的数据序列化,而函数不能序列化。

这里提到了。https:/nextjs.orgdocsapi-referencedata-fetchinggetInitialProps。

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

© www.soinside.com 2019 - 2024. All rights reserved.