axios 未捕获的错误:对象作为具有嵌套json对象的React子级无效

368yc8dk  于 2022-11-05  发布在  iOS
关注(0)|答案(1)|浏览(132)

当在类中使用axios async get和wait调用API时,我得到了错误;

Uncaught Error: Objects are not valid as a React child (found: object with keys {dhcp_lease_count, new_dhcp_lease_count, unracked_device_count, nodediscover_count, site_data}). If you meant to render a collection of children, use an array instead.

API正在将数据返回到res.data,但未定义state.data

lass MainContent extends Component {
    constructor(props) {
        super(props);

        this.state = {
            data: {},
            isLoaded: false,
            access_token: "my_token_xxxxx",
        }
    }

    componentDidMount = () => {
        this.getData()
    }

    getData = async () => {
        try {
            axios.defaults.headers.common['Authorization'] = "Token " + this.state.access_token;
            const res = await axios.get("http://localhost:7001/api/plugins/dashboard");
            this.setState({isLoaded: true, data: res.data})
        } catch (error) {
            console.log(Object.keys(error), error.message);
        }
    }

    render() {
        const { isLoaded, data } = this.state;
        return (
            <div>
                {isLoaded ? <h3>{data}</h3> : <h3>Loading...</h3>}
            </div>);
    }
}

如果我使用浏览器或 Postman

{
    "dhcp_lease_count": 169,
    "new_dhcp_lease_count": 19,
    "unracked_device_count": 4,
    "node_count": 135,
    "site_data": [
        {
            "site_temp_avg": 0,
            "site_rack_count": 0,
            "site_utilization": 0,
            "site_device_count": 0
        },
        {
            "site_temp_avg": "70.6",
            "site_rack_count": 8,
            "site_utilization": 57.375,
            "site_device_count": 167
        },
        {
            "site_temp_avg": 0,
            "site_rack_count": 0,
            "site_utilization": 0,
            "site_device_count": 0
        }
    ]
}

我认为它没有正确地将API数据解析为对象。
我正在尝试获取要在 Jmeter 板组件中显示的数据。sit_data将进入一个小表中。

llew8vvj

llew8vvj1#

您遇到的错误是因为您尝试直接在JSX代码中呈现响应对象。
如果您想查看应用程序上呈现的全部数据,可以尝试{JSON.stringify(data)}
否则,您应该操作该数据对象以正确呈现它。

相关问题