我正在运行一个反应项目,但我得到了这个。类型错误:无法读取未定义的属性“then”

我在 React 中有一个名为 StudentsList 的组件 并且正在尝试从服务文件夹访问学生。

这是显示我的代码的图像。 不知道为什么会收到错误Here is my StudentService.js file

Error am getting in the browser

dypzy2000 回答:我正在运行一个反应项目,但我得到了这个。类型错误:无法读取未定义的属性“then”

关于您的屏幕截图,有一个错字。 班级名称是 StudentService,您正在调用 StudentsService

,

在您的 StudentService 文件中, 看起来 getStudents() 没有返回。

试试这个:

class StudentService{
    getStudents(){
        return axios.get(STUDENT_REST_API_URL);
    }
}
,

您也可以使用 fetch API 来实现。

getStudents(){
 let students;
 fetch(url).then((response) => response.json()).then((data) => students = data);
 return students;
}

需要注意的关键是promise是如何解决的,数据是如何“返回”的。在您的情况下,您没有返回任何数据!

Axios 的工作方式与 fetch API 非常相似。

本文链接:https://www.f2er.com/4041.html

大家都在问