MERN栈新手:React页面获取到用户列表却显示无数据
MERN栈页面渲染用户列表失败问题
我是MERN栈新手,这个问题已经困扰我数小时。点击首页的View Users按钮后,页面跳转到View页面,我希望在此渲染用户列表,但页面始终显示「No data available」。

代码详情
首页(Landing Page)
import React, { useState, useEffect } from 'react'; import axios from 'axios'; import '../../src/App.css'; import { Button } from '@mui/material'; import { useNavigate } from 'react-router-dom'; const LandingPage = () => { const [alertShown, setAlertShown] = useState(false); useEffect(() => { if (!alertShown) { alert("You've successfully logged in!"); setAlertShown(true); } }, [alertShown]); const navigate = useNavigate(); const handleRedirectToView = () => { navigate('/view'); }; return ( <div style={{ backgroundImage: 'url("https://milonelawoffice.com/wp-content/uploads/2016/08/slide3.jpg")', width: 1280, height: 609, backgroundSize: 'cover', backgroundRepeat: 'no-repeat', paddingTop: 80 }} > <headingText style={{ fontSize: "40px", textAlign: "center" }}>Welcome to the Dashboard!</headingText> <br></br> <center> <Button onClick={handleRedirectToView} variant="contained" sx={{ backgroundColor: '#C1C8EB', color: '#0C142C' }}>View Users</Button> </center> </div> ); }; export default LandingPage;
View页面
import React, { useState, useEffect } from 'react'; import '../../src/App.css'; const View = () => { const [data, setData] = useState([]); useEffect(() => { fetch("http://localhost:4000/getUser", { method: "GET", }) .then((res) => res.json()) .then((data) => { setData(data.data); }); },[]); return( <div> {data && data.length > 0 ? ( <table> <thead> <tr> <th>Email</th> <th>Password</th> </tr> </thead> <tbody> {data.map(i => ( <tr key={i.email}> <td>{i.email}</td> <td>{i.password}</td> </tr> ))} </tbody> </table> ) : ( <p>No data available</p> )} </div> ) }; export default View;
问题现状
我尝试获取用户列表,预期能在View页面渲染出列表,但页面一直显示「No data available」,只有浏览器控制台能看到用户列表的JSON数组。
内容的提问来源于stack exchange,提问作者GallertGrindelwald
相关产品推荐
相关产品推荐

