在Next.js13中,服务器组件是默认启用的.我想知道是否需要将每个FETCH包装在一个单独的函数中,并将‘USE SERVER’添加到其中以隐藏该函数的代码,或者我是否可以在返回TSX的同一个函数中使用FETCH?
使用函数和‘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>
)
}
不带‘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>
)
}
这些版本中哪一个更安全?每个版本都应该在什么时候使用?