TypeError,但不是在React返回函数中



我遇到了一个问题,当我试图调用对象的属性时,我得到(TypeError: undefined不是对象);但是,在返回函数中调用它时确实会发生此错误。此外,该错误仅在调用对象的属性时发生,而不是在调用对象本身时发生。

我试图保持包含的代码简洁;虽然,我不太确定错误发生在哪里,所以可能有一些不必要的信息。此外,在代码中有注释,标记哪里会发生错误,哪里不会发生错误。

后端/模型/course.js

import mongoose from 'mongoose';
const courseSchema = mongoose.Schema({
_id: Number,
fields: Array,
number: Number,
name: String,
minCredits: Number,
maxCredits: Number,
description: String,
isSaved: { type: Boolean, default: false },
});
const course = mongoose.model('courses', courseSchema);
export default course;

后端/控制器/course.js

import CourseData from '../models/course.js';
export const getSpecificCourse = async(req, res)=> {
try {
const selectedCourse = await CourseData.findOne({ _id: req.query.courseId });

res.status(200).json(selectedCourse);
} catch (error) {
res.status(404).json({ message: error.message});
}
}

后端/线路/course.js

import express from 'express';
import { getSpecificCourse } from '../controllers/courses.js';
const router = express.Router();
router.get('/courseId', getSpecificCourse);
export default router;

后端/server.js

import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import courseRoutes from './routes/courses.js';
const app = express();
app.use(express.json());
app.use(cors());
app.use('/courses', courseRoutes);
const PORT = process.env.PORT || 5000;
mongoose.connect(mongoUrl, {dbName: "dbName"}) // Hidden for privacy
.then(() => app.listen(PORT, () =>
console.log(`Connection is established and running on port: ${PORT}`)
)).catch((err) => console.log(err.message));

前端/src/组件/CoursePage.js

import React, { useEffect, useState } from 'react';
import { useParams } from "react-router-dom";
import axios from 'axios';
import './styles.css';
export function CoursePage() {
const [isLoading, setLoading] = useState(true);
const [course, setCourse] = useState()
const { courseId } = useParams()
const url = 'http://localhost:5000/courses/courseId/?courseId=' + courseId;
useEffect(() => {
axios.get(url).then( (selectedCourse) => {
setCourse(selectedCourse.data);
setLoading(false);
} )
}, [])
console.log(course); // results in no error
console.log(course.number); // results in an error (occurs when calling any attribute)
if (isLoading) {
return <div>Loading...</div>
}

return (
<div>
{console.log(course)} // results in no error
{console.log(course.number)} // results in no error (consistent with each attribute)
</div>
);
}

首先,状态isLoading开始时为true, course开始时为undefined:

const [isLoading, setLoading] = useState(true);
const [course, setCourse] = useState()

然后,在它被定义之前,你尝试访问course:

// now the course is not defined yet.
console.log(course); // results in no error
console.log(course.number); // results in an error (occurs when calling any attribute)
if (isLoading) {
return <div>Loading...</div>
}

如果您将代码更改为:

if (isLoading) {
return <div>Loading...</div>
}
console.log(course); // results in no error
console.log(course.number); // results in an error (occurs when calling any attribute)

你的代码没有任何错误,因为isLoading被设置为false只有当课程状态被设置为接收对象。

最新更新