gpt4 book ai didi

How do I import an object from a client component into a server component, in Next.js?(如何在Next.js中将对象从客户端组件导入到服务器组件?)

转载 作者:bug小助手 更新时间:2023-10-25 12:50:37 24 4
gpt4 key购买 nike



I have a Next.js 13 app (using the app router) with a server component and a client component.

我有一个带有服务器组件和客户端组件的Next.js13应用程序(使用应用程序路由器)。


I am trying to import a plain JS object that I defined in the client component, into the server component:

我正在尝试将在客户端组件中定义的普通JS对象导入到服务器组件中:


// ClientComponent.js
'use client';

export const exportedObject = { foo: bar };

export default ClientComponent = () => { return <div>RCC</div> };

And:

以及:


// ServerComponent.js
import { exportedObject } from './ClientComponent';

// This log tells me the object is a function
console.log(exportedObject);

export default ServerComponent = () => {
// Trying to access exportedObject does not work, I get the same result as above
// (i.e. it is a function that will throw an error if run)
console.log(exportedObject);

return (<div>RSC</div>);
}

The exportedObject becomes a function for some reason, when importing it into the server component.

在将导出的对象导入到服务器组件中时,出于某种原因,它会变成一个函数。


Why is that and how could I fix it without turning ServeComponent into a client component?

为什么会这样?我如何才能在不将ServeComponent转换为客户端组件的情况下修复它?


更多回答

Have you tried moving the exportedObject to a different directory? Like utils/utils.js

您是否尝试过将导出的对象移动到其他目录?如utils/utils.js

I was able to solve it by extracting the object into its own file, without use client, as suggested by @kinduser. I still do not understand why the OP code does not work though.

我能够像@kinduser建议的那样,通过将对象提取到它自己的文件中来解决这个问题,而无需使用客户端。我仍然不明白为什么操作码不起作用。

优秀答案推荐
更多回答

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com