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

React中使用Axios获取JSON数据遍历显示为空的问题求助

问题解决:React组件渲染GraphQL返回的message文本为空或显示数字

问题描述

通过React组件调用GraphQL接口获取帖子数据,想要渲染每条数据的message文本,但页面渲染后内容为空;如果直接显示遍历变量data,页面只会显示一串数字。

原代码

const Forms = () => {
    const [messageText, setMessageText]: any = useState("");
    useEffect(() => {
        const getPosts = () => {
            axios.post('http://localhost:8080/graphql/', {
                query: `
  {
    getPosts(option: true) {
      id
      message
    }
  }  
  `
            })
                .then((res) => {
                    const andrey = res.data.data.getPosts
                    setMessageText(andrey)
                })
                .catch((error) => {
                    console.error(error)
                })
        };
        getPosts()
    }, [])
    console.log(messageText)
    return (
        <div>
            <div style={{alignItems: "center", justifyContent: "center", textAlign: "center"}}>
                {Object.keys(messageText).map((data: any) => (
                    <Form message={data.message}/>
                    ))}
            </div>
            <Input/>
        </div>
    );
};

export default Forms; 

问题原因

  1. 初始状态类型不匹配:messageText初始值设为空字符串"",但接口返回的是数组。初始渲染时Object.keys("")得到空数组,所以没有内容;当数据加载完成后,Object.keys(数组)返回的是数组的索引(字符串形式的数字),此时map里的data是索引值,不是帖子对象,自然data.message不存在,导致渲染为空,直接显示data就会显示索引数字。
  2. 未处理异步加载状态:数据加载是异步的,初始渲染时messageText还没拿到数据,没有对应的加载提示或兜底处理。

解决方案

修改代码如下:

import { useState, useEffect } from 'react';
import axios from 'axios';
import Form from './Form';
import Input from './Input';

const Forms = () => {
    // 初始值设为空数组,匹配接口返回的数据类型
    const [messageText, setMessageText] = useState([]);
    // 添加加载状态,处理异步加载过程
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const getPosts = async () => {
            try {
                const res = await axios.post('http://localhost:8080/graphql/', {
                    query: `
                    {
                        getPosts(option: true) {
                            id
                            message
                        }
                    }  
                    `
                });
                const posts = res.data.data.getPosts;
                setMessageText(posts);
            } catch (error) {
                console.error(error);
            } finally {
                // 无论请求成功或失败,都结束加载状态
                setLoading(false);
            }
        };
        getPosts();
    }, []);

    // 加载中显示提示
    if (loading) {
        return <div>加载中...</div>;
    }

    return (
        <div>
            <div style={{ alignItems: "center", justifyContent: "center", textAlign: "center" }}>
                {/* 直接遍历数组,每个post是帖子对象 */}
                {messageText.map((post) => (
                    // 必须添加唯一key,用接口返回的id最优
                    <Form key={post.id} message={post.message} />
                ))}
            </div>
            <Input />
        </div>
    );
};

export default Forms;

修改说明

  • 调整messageText初始值为[],和接口返回的数组类型一致,避免初始渲染时的遍历问题。
  • 去掉Object.keys,直接对messageText数组进行map遍历,此时每个post就是完整的帖子对象,可直接访问post.message。
  • 添加loading状态,在数据加载完成前显示加载提示,避免页面空白。
  • 改用async/await写法,让异步代码更简洁易读。
  • 给列表元素添加key属性,符合React列表渲染规范,消除控制台警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 21:52:43