reactjs - 在 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.
}
所以我的问题是为什么会发生这种情况,以及如何在客户端保持正确的对象类型。
解决方案
getInitialProps
序列化它返回的数据,函数不能序列化。
这里提到: https ://nextjs.org/docs/api-reference/data-fetching/getInitialProps
一旦实例作为组件的道具出现,您就需要重建实例。
推荐阅读
- html - 在 Django 中通过 Bootstrap 进行定位
- node.js - 从 firebase 下载文件并上传到 Stripe 进行身份验证
- python - 显示活动 conda 通道的命令
- javascript - 链接承诺不会将数据从一个 .then 传递到下一个
- sql - 检查一列的值是否在另一列中
- facebook - 如何让 Facebook Messenger 聊天机器人忽略与 FB 用户的收件箱对话?
- python - How to Solve KeyError in View Django
- algorithm - 有哪些算法可以比较两棵树之间的差异?
- button - 当我使用按钮显示工作表时,工作表被拉下后,再次自动显示
- pandas - 合并两列上的数据框时解决错误