首页
"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() {
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>
);
}
组件
import Link from "next/link";
export default function Courses({ courses }) {
return (
<div className="courses">
{courses?.map((course) => (
<div key={course.id} className="card">
<h2>{course.title}</h2>
<small>Level: {course.level}</small>
<p>{course.description}</p>
<Link href={course.link} target="_blank" className="btn">
Go to course
</Link>
</div>
))}
</div>
);
}
只想在 nextjs 的客户端页面使用“useState 和 useEffect”从本地 api 获取数据,但出现错误(setState 不是函数),请让我知道我在这里做错了什么。我是新人React 和 Nextjs
您错误地设置了
useState
钩子的状态变量和 setter 函数。状态变量是 setter 函数,应该设置在解构数组中,而不是像上面所做的那样设置为对象。这是使用 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();
}, []);