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

React中map函数导致页面空白问题求助

问题分析与解决

页面空白的核心原因是调用setArticles()时未传入接口返回的数据,导致articles状态变为undefined,而undefined无法执行map方法,触发静默错误(React生产环境会吞掉这类错误,直接导致页面空白)。

修复步骤:

  1. 正确更新状态
    将useEffect里的setArticles()改为setArticles(response),确保接口返回的数据存入状态:

    .then(response => setArticles(response))
    

    注意:如果后端返回的是嵌套结构(比如{ "results": [/* 文章列表 */] }),需要取对应的数组部分,比如setArticles(response.results),可以通过console.log(response)在控制台确认数据结构

  2. 给列表元素添加唯一key
    React要求列表渲染的元素必须有唯一key属性,避免性能问题和控制台警告,修改map部分代码:

    {articles.map(article =>{
        return <h2 key={article.id}> {article.title} </h2>
    })}
    

    若文章没有id字段,可用slug或其他唯一标识字段替代。

  3. 可选:添加加载状态优化体验
    新增加载状态,避免数据未返回时页面仅显示标题:

    const [articles,setArticles] = useState([])
    const [loading, setLoading] = useState(true) // 新增加载状态
    
    useEffect(()=>{
        fetch('http://127.0.0.1:8000/api/articles',{
            'method':'GET',
            headers: {
                'content-Type':'application/json',
                'Authorization':'Token a9714c85387c802207740a7bd8882f4a748733be',
            }
        })
        .then(response => response.json())
        .then(response => {
            setArticles(response)
            setLoading(false) // 数据加载完成后关闭加载状态
        })
        .catch(error => {
            console.log(error)
            setLoading(false) // 出错也关闭加载状态
        })
    },[])
    
    // 渲染部分
    return (
        <div className="App">
            <h3> Django & Reactjs Blog App</h3>
            {loading ? <p>加载中...</p> : (
                articles.map(article =>{
                    return <h2 key={article.id}> {article.title} </h2>
                })
            )}
        </div>
    );
    

验证方法

修改后打开浏览器控制台,查看Network标签确认接口返回正确的数组数据,同时检查Console标签是否有报错,确保状态更新逻辑和数据结构匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 10:25:20