Next.js 13.4.19客户端组件async/await报错,如何使用useState等钩子?
Next.js 13.4.19 客户端组件异步函数与React Hooks冲突问题
环境与项目结构
使用的Next.js版本:"next": "13.4.19"
项目结构:
--app -- layout.tsx -- page.tsx -- [id] --page.tsx
初始代码与错误
在[id]/page.tsx中编写如下代码:
"use client" import { Editor } from '@/components/editor'; import { useState, useRef, useEffect, useMemo } from 'react' export default async function PipelineDesignerEditorPage( { params }: { params: { pipelineId: string } } ) { console.log('params.pipelineId',params.pipelineId); const [loding, setLoding] = useState(false); const [pipelineData, setPipelineData] = useState({}); useEffect(() => { setLoding(true); let data = getPipeline(params.pipelineId); setPipelineData(data); setLoding(false); }, []); return ( <div style={{ width: '100%', height: `calc(100vh - 65px)` }}> <Editor pipeline={pipeline} /> </div> ) }
运行后触发错误:
Error: async/await is not yet supported in Client Components, only Server Components. This error is often caused by accidentally adding
'use client'to a module that was originally written for the server.
修改后的代码与问题
尝试直接在组件中异步获取数据,但问题仍未解决:
'use client' // 注:原文此处拼写为'user client',应为'use client' import { Editor } from '@/components/editor'; import { getPipeline } from '@/lib/pipelines/storage'; import { useState, useRef, useEffect, useMemo } from 'react' export default async function PipelineDesignerEditorPage( { params }: { params: { pipelineId: string } } ) { console.log('params.pipelineId',params.pipelineId); const pipeline = await getPipeline(params.pipelineId); const [loding, setLoding] = useState(false); useEffect(() => { console.log('useEffect'); setLoding(true); }, []); return ( <div style={{ width: '100%', height: `calc(100vh - 65px)` }}> <Editor pipeline={pipeline} /> </div> ) }
只有移除useState和useEffect后代码才能正常运行。
提问
这是否意味着我无法在app->[id]->page.tsx中使用useState和useEffect?那需要这些钩子实现的点击、加载等交互操作该如何处理?
内容的提问来源于stack exchange,提问作者user824624
相关产品推荐
相关产品推荐

