如何从MongoDB拉取数据并在React前端以卡片形式展示?
React端拉取MongoDB数据并渲染卡片实现方案
你提供的后端接口参考(已验证可用)
router.get('/ads', async (req,res,next)=>{ try{ const ads = await Ads.find(); return res.status(200).json({ success: true, count: ads.length, data: ads, }); } catch(err) { console.log(err); res.status(500).json({ error: 'server error' }); } });
接口返回示例:
前置注意事项
- 确保后端服务已启动,接口可以正常访问
- 提前解决跨域问题:可以在后端安装
cors包启用跨域,或者在React项目的package.json中配置"proxy": "你的后端服务地址(比如http://localhost:5000)"
完整实现代码示例
方法1:使用原生fetch实现(无需额外安装依赖)
import { useState, useEffect } from 'react' import './AdsList.css' // 卡片样式文件 const AdsList = () => { // 定义状态:广告列表、加载状态、错误信息 const [adsList, setAdsList] = useState([]) const [loading, setLoading] = useState(true) const [error, setError] = useState('') // 组件挂载时拉取数据 useEffect(() => { const fetchAds = async () => { try { // 替换成你自己的后端接口实际地址 const res = await fetch('http://你的后端地址/ads') const result = await res.json() if (result.success) { setAdsList(result.data) } else { setError('获取数据失败') } } catch (err) { setError('请求出错:' + err.message) } finally { setLoading(false) } } fetchAds() }, []) // 加载中展示 if (loading) return <div>加载中...</div> // 出错展示 if (error) return <div className="error">{error}</div> return ( <div className="ads-container"> <h2>广告列表</h2> <div className="cards-wrapper"> {/* 遍历广告列表,每条数据渲染一个独立卡片 */} {adsList.map(ad => ( <div key={ad._id} className="ad-card"> <h3>{ad.title}</h3> <p>{ad.description}</p> <p className="price">价格:¥{ad.price}</p> {/* 根据你实际的字段自行增减展示内容 */} </div> ))} </div> </div> ) } export default AdsList
方法2:使用axios实现(代码更简洁)
首先安装axios:npm install axios
import { useState, useEffect } from 'react' import axios from 'axios' import './AdsList.css' const AdsList = () => { const [adsList, setAdsList] = useState([]) const [loading, setLoading] = useState(true) const [error, setError] = useState('') useEffect(() => { const fetchAds = async () => { try { // 替换为实际后端接口地址 const res = await axios.get('http://你的后端地址/ads') if (res.data.success) { setAdsList(res.data.data) } } catch (err) { setError('请求出错:' + err.response?.data?.error || err.message) } finally { setLoading(false) } } fetchAds() }, []) // 渲染逻辑和上面fetch版本完全一致,此处省略重复代码 // ... } export default AdsList
卡片样式示例(AdsList.css)
.ads-container { max-width: 1200px; margin: 0 auto; padding: 20px; } .cards-wrapper { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; margin-top: 20px; } .ad-card { border: 1px solid #e5e7eb; border-radius: 8px; padding: 16px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); transition: all 0.3s; } .ad-card:hover { box-shadow: 0 4px 8px rgba(0,0,0,0.15); } .price { color: #f97316; font-weight: bold; margin-top: 12px; } .error { color: #ef4444; padding: 20px; text-align: center; }
关键说明
- 遍历列表时必须给每个卡片加唯一
key属性,这里直接用MongoDB自动生成的_id字段即可 - 展示字段要和你MongoDB集合里的字段对应,上面的title/description/price只是示例,你可以根据实际返回的字段修改
- 如果后端和前端端口不同,一定要先处理跨域问题,否则请求会被浏览器拦截
内容的提问来源于stack exchange,提问作者AHMAD IRSHAD
相关产品推荐
相关产品推荐

