英文:
How do I pass data from server component to client component in Next.js 13 app router?
问题
以下是翻译好的部分:
在Next.js 13应用程序路由中如何将数据从服务器组件传递到客户端组件?
我在page.tsx中调用了一个外部API,该API返回了一个人的城市信息。我想将这个城市信息传递给客户端组件,以便在客户端中显示和更改。如何最好地实现这一目标呢?在React中,我们可以使用Redux,但由于这是Next.js 13的服务器组件,我不太确定如何做。
app/page.tsx
const Page = async () => {
const city = await getCity();
const hotels = await getHotelsByCity({
city: city,
});
return (
<div className="pt-24 md:pt-28 flex md:flex-row md:flex-wrap flex-col">
{hotels &&
hotels.map((hotel) => {
<div>{hotel}</div>;
})}
</div>
);
};
export default Page;
app/components/Navbar/Location.tsx
"use client";
import useSelectLocationModal from "@/app/hooks/useSelectLocationModal";
export default function Location() {
const selectLocationModal = useSelectLocationModal();
return (
<div
className="flex items-center cursor-pointer"
onClick={() => selectLocationModal.onOpen()}
>
<p>{city}</p>
</div>
);
}
英文:
How to pass data from the server component to the client component in Next.js 13 app router?
I am calling an external API in page.tsx which gives the city of the person. I want to pass this city to the client component where this city can be displayed and changed. What will be the best way to achieve this? In React we can use redux but since this is next.js 13 server component not sure how to do it.
app/page.tsx
const Page = async () => {
const city = await getCity();
const hotels = await getHotelsByCity({
city: city,
});
return (
<div className="pt-24 md:pt-28 flex md:flex-row md:flex-wrap flex-col">
{hotels &&
hotels.map((hotel) => {
<div>{hotel}</div>;
})}
</div>
);
};
export default Page;
app/components/Navbar/Location.tsx
"use client";
import useSelectLocationModal from "@/app/hooks/useSelectLocationModal";
export default function Location() {
const selectLocationModal = useSelectLocationModal();
return (
<div
className="flex items-center cursor-pointer"
onClick={() => selectLocationModal.onOpen()}
>
<p>{city}</p>
</div>
);
}
答案1
得分: 2
你可以将数据作为 props 传递,只需确保它已序列化。
例如
export default async function Home() {
let data;
console.log("fetching data");
try{
const res = await fetch(process.env.API_URL + '/endpoint', {
headers: {
'Accept': 'application/json'
},
next: {
tags: ['homepage']
}
});
data = await res.json();
}
catch (e) {
console.log(e);
}
return (
<main>
<YourClientComponent data={data}/>
</main>
)
}
英文:
You can pass the data as props, you just need to make sure that it is serialized .
for instance
export default async function Home() {
let data;
console.log("fetching data");
try{
const res = await fetch(process.env.API_URL + '/endpoint', {
headers: {
'Accept': 'application/json'
},
next: {
tags: ['homepage']
}
});
data = await res.json();
}
catch (e) {
console.log(e);
}
return (
<main>
<YourClientComponent data={data}/>
</main>
)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论