我有这个简单的计数器
import React, { useState } from "react";
export default function SSRComponent() {
const [count, setCount] = useState(0);
const incrementCount = () => {
setCount((previousCount) => previousCount + 1);
};
return (
<div>
<h1>Server-Side Rendered Component</h1>
<p>Count: {count}</p>
<button onClick={incrementCount}>Increment</button>
</div>
);
}
尝试运行服务器时出现此错误
./components/Header.tsx
ReactServerComponentsError:
You're importing a component that needs useState. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.
,-[/home/dmytro/PhpstormProjects/prod/proudly-ukrainian/components/Header.tsx:1:1]
1 | import React, { useState } from "react";
: ^^^^^^^^
2 |
3 | export default function SSRComponent() {
4 | const [count, setCount] = useState(0);
`----
Maybe one of these should be marked as a client entry with "use client":
./components/Header.tsx
./app/layout.tsx
那么如何使用 Next.js 在 SSR 组件中使用简单状态?