You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React调用API展示学生数据报错:Uncaught ReferenceError: students is not defined

问题描述

尝试通过自建API获取学生信息及所选课程并在React组件中展示,API地址为https://localhost:44309/api/Students,返回数据如下:

[
  {
    "id": 1,
    "lastName": "Rizal",
    "firstName": "Jose",
    "courses": [
      "C#",
      "Javascript",
      "CSS"
    ]
  },
  {
    "id": 2,
    "lastName": "Bonifacio",
    "firstName": "Andres",
    "courses": [
      "HTML",
      "ASP.NET MVC"
    ]
  },
  {
    "id": 3,
    "lastName": "Sora",
    "firstName": "Tandang",
    "courses": [
      "CSS",
      ".NET"
    ]
  }
]

使用的React组件代码如下:

import React from "react"
import { useState, useEffect } from "react";


const StudentList = () => {
    const [students, setStudent] = useState([]);
    
    const getData = async () => {
      const response = await fetch("https://localhost:44309/api/students");
      const data = await response.json()
      setStudent(data)
    }
  
    useEffect(() => {
        getData()
    }, []);

    return (
        <div className="student-list">
            <h2>Students and their courses</h2>
            {students.map(student => (
                <div className="student-preview" key={student.id}>
                    <p>{ student.fname } { student.lname }</p>
                    <p>{ student.courses }</p>
                </div>
            ))}
        </div>
    )
}

export default StudentList

运行时出现错误:Uncaught ReferenceError: students is not defined,需要排查问题原因。


问题排查与解决

1. 状态更新函数命名不匹配

你定义的状态变量是students(复数),但对应的更新函数写成了setStudent(单数),这会导致状态无法正确更新,虽然不是报错的直接原因,但属于核心问题:

// 原代码
const [students, setStudent] = useState([]);
// 修正为
const [students, setStudents] = useState([]);

// 同时在getData函数里,更新状态的代码也要改成
setStudents(data);

2. 字段名不匹配(潜在渲染问题)

API返回的学生姓名是firstName和lastName,但你在渲染时用了student.fname和student.lname,这会导致姓名显示为空或者undefined,需要修正字段名:

<p>{ student.firstName } { student.lastName }</p>

3. 关于students is not defined的直接原因

从你提供的代码看,students是通过useState在组件内部定义的,理论上作用域没问题。但如果报错确实存在,可能是以下情况:

  • 代码运行时存在语法解析错误,比如useState导入拼写错误(你当前导入是对的,但可以再检查)
  • 组件内部存在其他未展示的代码,误写了students的引用
  • 开发环境缓存问题,可以尝试重启开发服务器,清除缓存后重新运行

另外,建议给fetch请求增加错误处理,避免请求失败时导致的异常:

const getData = async () => {
  try {
    const response = await fetch("https://localhost:44309/api/students");
    if (!response.ok) {
      throw new Error(`请求失败:${response.status}`);
    }
    const data = await response.json();
    setStudents(data);
  } catch (err) {
    console.error("获取学生数据出错:", err);
  }
};

修复后的完整代码

import React from "react"
import { useState, useEffect } from "react";

const StudentList = () => {
    const [students, setStudents] = useState([]);
    
    const getData = async () => {
      try {
        const response = await fetch("https://localhost:44309/api/students");
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        setStudents(data);
      } catch (error) {
        console.error('获取学生数据失败:', error);
      }
    }
  
    useEffect(() => {
        getData();
    }, []);

    return (
        <div className="student-list">
            <h2>Students and their courses</h2>
            {students.map(student => (
                <div className="student-preview" key={student.id}>
                    <p>{ student.firstName } { student.lastName }</p>
                    <div>
                        <strong>所选课程:</strong>
                        <ul>
                            {student.courses.map(course => (
                                <li key={course}>{course}</li>
                            ))}
                        </ul>
                    </div>
                </div>
            ))}
        </div>
    )
}

export default StudentList

内容的提问来源于stack exchange,提问作者Cedd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 12:57:12