React与Next.js中setState is not a function错误排查求助
问题分析与修复
你的错误根源在于useState的解构方式错误:React的useState Hook返回的是一个包含状态值和更新函数的数组,而非对象,你误用了对象解构语法,导致setCourse和setLoading被解析为undefined,调用时自然会报“setState is not a function”错误。
修正后的首页代码
"use client"; import { useState, useEffect } from "react"; import Loading from "./loading"; import Link from "next/link"; import Courses from "./components/courses"; export default function HomePage() { // 改为数组解构,这是useState的正确用法 const [course, setCourse] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { async function fetchCourses() { const res = await fetch("/api/courses"); const data = await res.json(); setCourse(data); setLoading(false); } fetchCourses(); }, []); if (loading) { return <Loading />; } return ( <div> <h1>Welcome to next website</h1> <Courses courses={course} /> </div> ); }
组件代码说明
你的Courses组件写法没有问题,使用可选链courses?.map能避免空数组或undefined时的报错,逻辑是合理的。
内容的提问来源于stack exchange,提问作者Mohsin Abbas
相关产品推荐
相关产品推荐

