gpt4 book ai didi

Should I use 'use server' in all functions that fetch secret data within server components in Next.js?(我应该在所有在Next.js的服务器组件中获取机密数据的函数中使用‘use server’吗?)

转载 作者:bug小助手 更新时间:2023-10-25 18:21:52 28 4
gpt4 key购买 nike



Server components are enabled by default in Next.js 13. I'm wondering if I need to wrap each fetch in a separate function and add 'use server' to it to hide the function's code, or can I simply use fetch in the same function that returns the TSX?

在Next.js13中,服务器组件是默认启用的。我想知道是否需要将每个FETCH包装在一个单独的函数中,并将‘USE SERVER’添加到其中以隐藏该函数的代码,或者我是否可以在返回TSX的同一个函数中使用FETCH?


Code wrap with function and 'use server':

使用函数和‘USE SERVER’的代码包装:


async function getData() {
'use server'
const res = await fetch('http://localhost:3001/test',{cache:'no-cache'})

return res.json()
}

interface Test{
age:number,
name:string,
likes:number,
}

export default async function Home() {

const tests:Test[] = await getData()

return (
<div className='flex flex-row'>
{tests.map((test)=>{
return (
<div>
<div>
{test.name}
</div>
<div>
{test.age}
</div>
<div>
Likes: {test.likes}
</div>
</div>
)
})}
</div>
)
}

Code without 'use server':

不带‘Use Sever’的代码:


interface Test {
age:number,
name:string,
likes:number,
}

export default async function Home() {

const res = await fetch('http://localhost:3001/test',{cache:'no-cache'})

const tests:Test[] = await res.json()

return (
<div className='flex flex-row'>
{tests.map((test)=>{
return (
<div>
<div>
{test.name}
</div>
<div>
{test.age}
</div>
<div>
Likes: {test.likes}
</div>
</div>
)
})}
</div>
)
}

Which of these versions is more secure, and when should each be used?

这些版本中哪一个更安全?每个版本都应该在什么时候使用?


更多回答
优秀答案推荐

As you said, within the app router, Next.js uses Server Components by default (until a "use client" is added at the top). They get called on the server, and returned to the browser as HTML (containing what's in the JSX, the return part). No JavaScript code from the component reaches the browser: you don't have to do or add anything.

正如您所说,在应用程序路由器中,Next.js默认使用服务器组件(直到在顶部添加了“Use Client”)。它们在服务器上被调用,并作为HTML返回给浏览器(包含JSX中的内容,即返回部分)。组件中的任何JavaScript代码都不会到达浏览器:您不需要执行任何操作或添加任何内容。


The "use server" is introduced for a specific feature of the app router, called Server Actions, where out of functions (with "use server") passed to form elements, you get API routes.

“使用服务器”是为应用程序路由器的一个特定功能引入的,称为服务器操作,其中传递给表单元素的函数(通过“使用服务器”)将获得API路由。


It may seem odds, but "use server" is not the opposite of "use client". A component with no "use client" at the top is the opposite of "use client". And "use server" is totally different.

这似乎不太可能,但“使用服务器”并不是“使用客户端”的对立面。顶部没有“使用客户端”的组件是“使用客户端”的反义词。和“使用服务器”是完全不同的。


更多回答

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