【问题标题】:TypeError, but not when inside React return functionTypeError,但不是在 React 返回函数中
【发布时间】:2021-10-26 17:29:33
【问题描述】:

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

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

后端/models/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>
  );
}

【问题讨论】:

    标签: javascript node.js reactjs mongodb mongoose


    【解决方案1】:

    首先,状态 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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-18
      • 2020-08-25
      • 1970-01-01
      • 2021-06-17
      • 2018-05-01
      • 2021-05-01
      • 2017-06-24
      • 1970-01-01
      相关资源
      最近更新 更多