简体   繁体   中英

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 . But in return I get nothing but a html page in return and these are are shown in the browser console.

错误1

错误2

And this is how my React looks like to get the data using 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.


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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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