[英]How to get MongoDB values and display in a table using ReactJS
我正在尝试使用ReactJS
MongoDB
数据库中的数据填充到table
中。 但是作为回报,除了html
页面之外,我什么也没有得到,这些都显示在浏览器控制台中。
这就是我的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.