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

wwwo4jvm  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(133)

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

  1. import Image from "next/image";
  2. import styles from "./page.module.css";
  3. import { cookies } from "next/headers";
  4. export default function Home() {
  5. function setCookie() {
  6. //code to set cookies
  7. }
  8. return (
  9. <div>
  10. <div>hello</div>
  11. <button onClick={setCookie}>Hello</button>
  12. </div>
  13. );
  14. }

但显示错误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

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

/app/page.tsx

  1. import { Button } from "@/components/Button";
  2. export default function Home() {
  3. return (
  4. <div>
  5. <div>hello</div>
  6. <Button />
  7. </div>
  8. );
  9. }

/components/Button.tsx

  1. "use client";
  2. import { setCookie } from "./setCookie";
  3. export function Button() {
  4. return (
  5. <form action={setCookie}>
  6. <button type="submit">Hello</button>
  7. </form>
  8. );
  9. }

/components/setCookie.tsx

  1. "use server";
  2. import { cookies } from "next/headers";
  3. export async function setCookie() {
  4. cookies().set("foo", "bar");
  5. }
展开查看全部

相关问题