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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:52:50