简体   繁体   English

如何使用ReactJS获取MongoDB值并显示在表中

[英]How to get MongoDB values and display in a table using ReactJS

I am trying to populate data from my MongoDB database in a table using ReactJS . 我正在尝试使用ReactJS MongoDB数据库中的数据填充到table中。 But in return I get nothing but a html page in return and these are are shown in the browser console. 但是作为回报,除了html页面之外,我什么也没有得到,这些都显示在浏览器控制台中。

错误1

错误2

And this is how my React looks like to get the data using axios 这就是我的React看起来如何使用axios获取数据的axios

import React, { Component } from "react";
import "react-datepicker/dist/react-datepicker.css";
import axio from "axios";

const ShowAssignments = (props) => (
  <tr>
    <td>{props.assignment.assignmentName}</td>
    <td>{props.assignment.assignmentDescription}</td>
    <td>{props.assignment.courseName}</td>
    <td>{props.assignment.assignmentDueDate}</td>
  </tr>
);

export default class AllAssignments extends Component {
  constructor(props) {
    super(props);

    this.state = {
      assignmentName: "",
      assignmentDescription: "",
      courseName: "",
      assignmentDueDate: "",
      allAssignments: []
    };
  }

  componentDidMount() {
    axio
      .get("http://localhost:4000/courseweb/assignments")
      .then(res => {
        this.setState({
          allAssignments: res.data
        });
      })
      .catch(err => {
        console.log(err);
      });
  }

  getRows() {
    return this.state.allAssignments.map((currentAssignment, id) => {
        return <ShowAssignments book={currentAssignment} key={id} />
    });
  }
  render() {
    return (
      <div id="content-wrapper">
        <div className="container-fluid">
          <ol className="breadcrumb">
            <li className="breadcrumb-item">
              <a href={`/instructor/${this.props.username}`}>Home</a>
            </li>
            <li className="breadcrumb-item active">Update Assignment</li>
          </ol>

          <h1>Update Assignments</h1>
          <hr />
          <p>Update due dates of Assignments</p>
          <br />
          <table className="table table-striped">
            <thead>
              <tr>
                <th>Assignment Name</th>
                <th>Assignment Description</th>
                <th>Course Name</th>
                <th>Due Date</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>{this.getRows()}</tbody>
          </table>
        </div>
      </div>
    );
  }
}

And this is my server.js which handles the backend. 这是我处理后端的server.js


const Bundler = require("parcel-bundler");


const bundler = new Bundler("./src/index.html");

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");

const InstructorDB = require("./public/DBModels/InstructorDB");
const AssignmentDB = require('./public/DBModels/AssignmentDb');

const app = express();
const router = express.Router();

app.use(bodyParser.json());
app.use(cors());
app.use("/courseweb", router);
app.use(bundler.middleware());

//connect to books database
mongoose.connect("mongodb://127.0.0.1:27017/courseweb", { useNewUrlParser: true });

const connection = mongoose.connection;
connection.once("open", () => {
  console.log("Connected to MongoDB via port 27017");
});

app.listen(4000, () => {
  console.log("Listening to port 4000");
});

//add a course - not my part though
router.route("/course/add").post((req, res) => {
  let instructorDB = new instructorDB(req.body);
  instructorDB
    .save()
    .then(bookDB => {
      res.status(200).send(`${bookDB} Added!`);
    })
    .catch(err => {
      res.status(400).send({ message: err });
    });
});

//get courses to-be accepted count
router.route("/courses").get((req, res) => {
  InstructorDB.countDocuments({}, function(err, count) {
    res.status(200).send(`${count}`);
  });
});

//add an assignment
router.route('/assignment/add').post((req, res) => {
  let assignmentDb = new AssignmentDB(req.body);
  assignmentDb.save().then((assignment) => {
    res.status(200).send(assignment);
  }).catch((err) => {
    res.status(400).send({message: err});
  });
});

//get all assignments, this is where I should get the values for this question
router.route('/assignments').get((req, res) => {
  AssignmentDB.find((err, assignments) => {
    if(err) throw err;
    res.status(200).send("Hi");
  });
});

Can someone please tell me where I have gone wrong? 有人可以告诉我我哪里出问题了吗?

Make it defensive 使其具有防御性

First step in making more solid code is to have an empty state or some sort of protection against crashes. 制作更稳定的代码的第一步是要具有空状态或某种防止崩溃的保护措施。

A simple fix here that will show you more info is this line 这行是一个简单的修复程序,它将向您显示更多信息

  getRows() {
    if (!this.state.allAssignments && !this.state.allAssignments.length) return null;
    return this.state.allAssignments.map((currentAssignment, id) => {
        return <ShowAssignments book={currentAssignment} key={id} />
    });
  }

then make some logs to see what values you have in the state at each rerender. 然后制作一些日志,以查看每次重新渲染时状态下的值。

  getRows() {
    console.log(this.state);
    if (!this.state.allAssignments && !this.state.allAssignments.length) return null;
    return this.state.allAssignments.map((currentAssignment, id) => {
        return <ShowAssignments book={currentAssignment} key={id} />
    });
  }

Do this first and see if there's even data in your state. 首先执行此操作,看看您的状态中是否还有数据。 It will probably show that you need to implement the lifecycle method componentDidUpdate to handle data coming in. 它可能表明您需要实现生命周期方法componentDidUpdate来处理传入的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM