如何在Next.js 13应用程序路由中从服务器组件传递数据到客户端组件?

huangapple go评论60阅读模式
英文:

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 () =&gt; {
  const city = await getCity();

  const hotels = await getHotelsByCity({
    city: city,
  });

  return (
    &lt;div className=&quot;pt-24 md:pt-28 flex md:flex-row md:flex-wrap flex-col&quot;&gt;
      {hotels &amp;&amp;
        hotels.map((hotel) =&gt; {
          &lt;div&gt;{hotel}&lt;/div&gt;;
        })}
    &lt;/div&gt;
  );
};

export default Page;

app/components/Navbar/Location.tsx

&quot;use client&quot;;

import useSelectLocationModal from &quot;@/app/hooks/useSelectLocationModal&quot;;

export default function Location() {
  const selectLocationModal = useSelectLocationModal();

  return (
    &lt;div
      className=&quot;flex items-center cursor-pointer&quot;
      onClick={() =&gt; selectLocationModal.onOpen()}
    &gt;
      &lt;p&gt;{city}&lt;/p&gt; 

    &lt;/div&gt;
  );
}

答案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(&quot;fetching data&quot;);
    try{
        const res = await fetch(process.env.API_URL + &#39;/endpoint&#39;, {
            headers: {
                &#39;Accept&#39;: &#39;application/json&#39;
            },
            next: {
                tags: [&#39;homepage&#39;]
            }
        });
        data = await res.json();
    }
    catch (e) {
        console.log(e);
    }

    return (
        &lt;main&gt;
            &lt;YourClientComponent data={data}/&gt;
        &lt;/main&gt;
    )
}

huangapple
  • 本文由 发表于 2023年6月2日 00:51:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76384104.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定