You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从MongoDB Atlas取数并在React组件MyPatient.js中循环渲染

问题

我已经实现了一个从MongoDB Atlas获取数据的后端接口,代码如下:

users.get('/get-data', function(req, res, next){ 
  var resultArray=[]; 
  MongoClient.connect(url, function(err, db){ 
    assert.equal(null, err); 
    var cursor=db.collection('users').find(); 
    cursor.forEach(function(doc, err){ 
      assert.equal(null, err); 
      resultArray.push(doc); 
    }, function(){ 
      db.close(); 
      res.render('Mypatient', {items: resultArray}) 
    }) 
  }) 
}

这个接口运行正常,控制台能输出结果,但目前是用res.render渲染到模板页面。现在我需要把这些数据传递到React项目的MyPatient.js组件中,该组件现有结构如下:

<div className="appoint_class">
  <ListGroup>
    <ListGroup.Item action variant="primary" className="list_group">
      <h4 style={{ textAlign: "start" }}>Mr. Shawn Louis</h4>
      <h6 style={{ textAlign: "start" }}>Cat</h6>
    </ListGroup.Item>
  </ListGroup>
</div>

请问如何实现前后端数据传递,并在前端通过循环渲染数据?

解决方案

没问题,我来一步步帮你搞定这个前后端数据传递和渲染的事儿~

1. 先改后端接口,返回JSON格式数据

你现在的后端用res.render是给模板引擎(比如EJS、Pug)用的,React需要的是纯JSON数据,所以把接口改成返回JSON就行:

users.get('/get-data', function(req, res, next){ 
  var resultArray=[]; 
  MongoClient.connect(url, function(err, db){ 
    assert.equal(null, err); 
    var cursor=db.collection('users').find(); 
    cursor.forEach(function(doc, err){ 
      assert.equal(null, err); 
      resultArray.push(doc); 
    }, function(){ 
      db.close();
      // 把res.render换成res.json,直接返回JSON数据
      res.json({ items: resultArray }); 
    }) 
  }) 
}

这样前端请求这个接口时,就能拿到结构化的用户数据了。

2. 在React组件里请求并渲染数据

在MyPatient.js里,我们用React的useState存数据,useEffect在组件挂载时请求后端接口,然后循环渲染每一条数据:

import React, { useState, useEffect } from 'react';
import { ListGroup } from 'react-bootstrap'; // 假设你用的是react-bootstrap的组件

function MyPatient() {
  // 用状态保存从后端拿到的患者数据
  const [patients, setPatients] = useState([]);

  // 组件一挂载就请求数据
  useEffect(() => {
    fetch('/get-data') // 这里的路径要和后端接口完全一致,要是前后端跨域得额外配置CORS
      .then(res => res.json())
      .then(data => {
        // 把拿到的数据存到状态里
        setPatients(data.items);
      })
      .catch(err => {
        console.error('加载数据出错啦:', err);
      });
  }, []); // 空数组确保只在组件挂载时执行一次

  // 循环渲染每一条患者数据
  return (
    <div className="appoint_class">
      <ListGroup>
        {patients.map((patient, index) => (
          <ListGroup.Item 
            key={patient._id || index} // 优先用数据库的_id当唯一key,没有的话用index
            action 
            variant="primary" 
            className="list_group"
          >
            <h4 style={{ textAlign: "start" }}>{patient.name}</h4> {/* 这里要换成你MongoDB里的实际字段名,比如fullName */}
            <h6 style={{ textAlign: "start" }}>{patient.petType}</h6> {/* 同样换成你数据库里的字段,比如animal */}
          </ListGroup.Item>
        ))}
      </ListGroup>
    </div>
  );
}

export default MyPatient;

3. 几个要注意的点

  • 字段匹配:上面代码里的patient.name和patient.petType一定要替换成你MongoDB集合里实际的字段名,不然会显示不出来哦!
  • 跨域问题:如果你的React项目跑在3000端口,后端跑在5000这种不同端口,得在后端配置CORS。先安装cors包:
    npm install cors
    
    然后在后端代码里引入并使用:
    const cors = require('cors');
    app.use(cors()); // 要在注册路由之前加这句
    
  • key属性:循环渲染React元素时必须加唯一的key,用数据库文档的_id是最好的选择,比用index更稳定。

内容的提问来源于stack exchange,提问作者Rutuja_Bhate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 13:07:40