查找所有文档获取响应结果,错误未定义

问题描述 投票:0回答:1

我在尝试执行 MongoDB Mern Stack 教程这里时遇到了另一个错误。通过应用程序添加数据效果很好,但现在即使数据库中有数据,我也无法在主页上显示所有结果。当弹出警报框时,它会显示

undefined
作为错误。主页只显示一个空表,但除了数据之外其他所有内容都显示。

//record.js

recordRoutes.route("/record").get(function (req, res) {
 let db_connect = dbo.getDb("todolist");
 db_connect
   .collection("records")
   .find({})
   .toArray(function (err, result) {
    if (err) throw err;
    res.json(result);
  });
});
//recordList.js

import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
const Record = (props) => (
  <tr>
    <td>{props.record.name}</td>
    <td>{props.record.position}</td>
    <td>{props.record.level}</td>
    <td>
      <Link className="btn btn-link" to={`/edit/${props.record._id}`}>
        Edit
      </Link>{" "}
      |
      <button
        className="btn btn-link"
        onClick={() => {
          props.deleteRecord(props.record._id);
        }}
      >
        Delete
      </button>
    </td>
  </tr>
);
export default function RecordList() {
  const [records, setRecords] = useState([]);
  // This method fetches the records from the database.
  useEffect(() => {
    function getRecords() {
      const response = fetch(`http://localhost:5000/record/`);
      if (!response.ok) {
        const message = `An error occurred: ${response.status} - ${response.statusText}`;
        window.alert(message);
        return;
      }
      const records = response.json();
      setRecords(records);
      return records;
    }
    getRecords();
    return;
  }, []);
  // This method will delete a record
  async function deleteRecord(id) {
    await fetch(`http://localhost:5000/${id}`, {
      method: "DELETE",
    });
    const newRecords = records.filter((el) => el._id !== id);
    setRecords(newRecords);
  }
  // This method will map out the records on the table
  function recordList() {
    return records.map((record) => {
      return (
        <Record
          record={record}
          deleteRecord={() => deleteRecord(record._id)}
          key={record._id}
        />
      );
    });
    
  }
  // This following section will display the table with the records of individuals.
  return (
    <div>
      <h3>Record List</h3>
      <table className="table table-striped" style={{ marginTop: 20 }}>
        <thead>
          <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Level</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>{recordList()}</tbody>
      </table>
    </div>
  );
}
javascript reactjs node.js response fetch-api
1个回答
0
投票

问题是

fetch
是一个异步函数。你必须使用await从API获取数据。

您的

useEffect
将如下所示:

useEffect(() => {
    async function getRecords() {
      const response = await fetch(`http://localhost:5000/record/`); // add await keyword here
      if (!response.ok) {
        const message = `An error occurred: ${response.status} - ${response.statusText}`;
        window.alert(message);
        return;
      }
      const records = response.json();
      setRecords(records);
      // no need to return here
    }
    getRecords();
    // no need of return here
  }, []);

希望对你有帮助

© www.soinside.com 2019 - 2024. All rights reserved.