如何设置cookie按钮点击next.js应用程序路由

wwwo4jvm  于 2023-04-12  发布在  其他
关注(0)|答案(1)|浏览(113)

我尝试使用下面的代码设置cookie。

import Image from "next/image";
import styles from "./page.module.css";
import { cookies } from "next/headers";

export default function Home() {
  function setCookie() {

    //code to set cookies

  }

  return (
   <div>
      <div>hello</div>
      <button onClick={setCookie}>Hello</button>
    </div>
  );
}

但显示错误Uncaught Error: Event handlers cannot be passed to Client Component props. <button onClick={function} children=...> If you need interactivity, consider converting part of this to a Client Component.
所以我在文件的顶部添加了'use client'
之后显示另一个错误You're importing a component that needs next/headers. That only works in a Server Component but one of its parents is marked with "use client", so it's a Client Component
我正在遵循next.js应用路由(不是页面路由)的文档。我不知道我哪里做错了。请帮帮我我是next.js的新手

fcy6dtqo

fcy6dtqo1#

检查这个:https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions这允许我们通过action props在客户端组件中使用服务器组件功能。
示例:
next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = { experimental: { serverActions: true } };

module.exports = nextConfig

/app/page.tsx

import { Button } from "@/components/Button";

export default function Home() {
  return (
    <div>
      <div>hello</div>
      <Button />
    </div>
  );
}

/components/Button.tsx

"use client";
import { setCookie } from "./setCookie";

export function Button() {
  return (
    <form action={setCookie}>
      <button type="submit">Hello</button>
    </form>
  );
}

/components/setCookie.tsx

"use server";
import { cookies } from "next/headers";

export async function setCookie() {
  cookies().set("foo", "bar");
}

相关问题