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

React本地项目空白页求助:需展示简历与API数据

React项目本地运行页面空白(MUI组件)的排查与修复

以下是针对你代码中导致页面空白的问题及修复方案:

核心问题及修复

1. MUI版本兼容问题

如果你的项目用的是MUI v5,makeStyles已经被官方废弃,继续使用会直接抛出错误,导致组件无法渲染。可以直接改用MUI v5推荐的sx属性来设置样式,或者使用styled API。

2. 缺失MUI主题提供者

MUI的所有组件必须在ThemeProvider的包裹下才能正常渲染,若根组件未添加这个提供者,组件会因缺少主题上下文而无法显示。

3. API请求错误未处理

代码里用的是示例API地址,请求必然失败,且没有错误捕获逻辑,未处理的Promise异常可能导致组件渲染中断。需要替换为真实可用的API,同时添加错误处理。

4. PDF路径错误

public目录下的资源不需要加public/前缀,且路径必须用正斜杠(/),反斜杠(\)会导致资源定位失败,也可能影响页面渲染。


修改后的完整代码

import React, { useState, useEffect } from 'react';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import { Grid, Typography, Link } from '@mui/material';

// 创建MUI主题(v5版本必须)
const theme = createTheme();

function App() {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    // 替换为你实际使用的免费API地址,这里用公开测试API举例
    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then((response) => {
        // 检查请求是否成功
        if (!response.ok) throw new Error('API请求失败');
        return response.json();
      })
      .then((json) => {
        setData(json);
      })
      .catch((err) => {
        setError(err.message);
        console.error('请求出错:', err);
      });
  }, []);

  return (
    <ThemeProvider theme={theme}>
      {/* 用sx属性替代makeStyles设置样式 */}
      <Grid container spacing={3} sx={{ flexGrow: 1, padding: '2rem' }}>
        <Grid item xs={12}>
          <Typography variant="h2">Hello BeyondMD!</Typography>
        </Grid>
        <Grid item xs={12}>
          <Link 
            href="/Resume+Template.pdf" 
            target="_blank" 
            rel="noopener noreferrer"
            color="primary"
          >
            查看我的简历
          </Link>
        </Grid>
        {/* 渲染API数据 */}
        {data && (
          <Grid item xs={12}>
            <Typography variant="body1">API返回数据:{data.title}</Typography>
          </Grid>
        )}
        {/* 渲染错误信息 */}
        {error && (
          <Grid item xs={12}>
            <Typography variant="body1" color="error">错误:{error}</Typography>
          </Grid>
        )}
      </Grid>
    </ThemeProvider>
  );
}

export default App;

额外检查步骤

  1. 确认MUI依赖安装正确:如果是v5版本,需安装@mui/material @emotion/react @emotion/styled;v4版本则安装@material-ui/core
  2. 打开浏览器控制台(F12)查看具体错误信息,这是排查页面空白最有效的方式
  3. 确认public目录下确实存在Resume+Template.pdf文件,文件名和大小写完全匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 11:16:01