首页 > 解决方案 > TypeError,但不是在 React 返回函数中

问题描述

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

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

后端/模型/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/components/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>
  );
}

标签: javascriptnode.jsreactjsmongodbmongoose

解决方案


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

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

然后,您尝试在定义之前访问课程:

// 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。


推荐阅读