Next.js使用useState触发ReactServerComponentsError求助
解决Next.js中useState触发ReactServerComponentsError的问题
你的问题核心是Next.js App Router默认所有组件都是Server Component,而useState这类React客户端钩子只能在Client Component中使用,必须显式声明组件为客户端组件。
正确解决方案
在你的Faq.js文件最顶部(所有import语句之前)添加"use client";指令,就能让组件成为Client Component,从而正常使用useState。
修正后的完整代码:
// ./src/app/services/Faq.js "use client"; import React, { useState } from 'react'; const FAQ = () => { const faqData = [ { question: "What is outsourcing?", answer: "Our pricing is flexible and depends on the scope and complexity of your project. We offer competitive rates and can provide a detailed quote after discussing your requirements.", }, { question: "What do I need to get started on my project?", answer: "You can reach our support team by emailing support@kargakarga.comment. We typically respond within 24 hours during business days.", }, { question: "Why is it beneficial to outsource the art component?", answer: "Yes, we offer a 30-day money-back guarantee. If you're not satisfied with our services, please contact us for a refund.", }, ]; const [openQuestionIndex, setOpenQuestionIndex] = useState(-1); const toggleAnswer = (index) => { setOpenQuestionIndex((prevIndex) => (prevIndex === index ? -1 : index)); }; return ( <div> <div className="p-4"> <h1 className="text-2xl font-semibold mb-6">Frequently Asked Questions</h1> <div className="space-y-4"> {faqData.map((item, index) => ( <div key={index} className="border rounded p-4 shadow-md"> <div className="cursor-pointer" onClick={() => toggleAnswer(index)} > <h2 className="text-lg font-semibold">{item.question}</h2> </div> {index === openQuestionIndex && ( <p className="text-gray-600 mt-2">{item.answer}</p> )} </div> ))} </div> </div> </div> ); }; export default FAQ;
为什么版本2无效?
defineComponent是Next.js用于创建Server Component的API,而Server Component不支持客户端状态管理(比如useState)、事件处理(比如onClick)这类客户端交互逻辑,所以你的版本2无法实现折叠展开的功能,这并不是正确的方向。
内容的提问来源于stack exchange,提问作者Hazal Kaya
相关产品推荐
相关产品推荐

