簡體   English   中英

如何使用ReactJS獲取MongoDB值並顯示在表中

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

我正在嘗試使用ReactJS MongoDB數據庫中的數據填充到table中。 但是作為回報,除了html頁面之外,我什么也沒有得到,這些都顯示在瀏覽器控制台中。

錯誤1

錯誤2

這就是我的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>
    );
  }
}

這是我處理后端的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");
  });
});

有人可以告訴我我哪里出問題了嗎?

使其具有防御性

制作更穩定的代碼的第一步是要具有空狀態或某種防止崩潰的保護措施。

這行是一個簡單的修復程序,它將向您顯示更多信息

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

然后制作一些日志,以查看每次重新渲染時狀態下的值。

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

首先執行此操作,看看您的狀態中是否還有數據。 它可能表明您需要實現生命周期方法componentDidUpdate來處理傳入的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM