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

React新手使用axios发GET请求传入硬编码对象数组报错如何解决

问题原因

axios.get() 第一个入参要求为接口URL字符串,你直接传入了硬编码的对象数组,不符合axios的调用规范,因此触发报错。
你的猜测不准确:const变量可以传入axios,但必须符合入参要求的类型,不是任意类型的const变量都能直接传入axios使用。

解决方案

根据你的实际需求选择对应方案:

场景1:仅使用当前硬编码数据,无需发起网络请求

不需要调用axios,直接使用你定义的数组即可,参考代码如下:

import { useState, useEffect } from 'react'

// 硬编码的事件数据
const eventList = [
    {
        "description": "",
        "durationday": "fullday",
        "end": "null",
        "id": 0,
        "location": "",
        "start": "null",
        "title": "",
    },
    {
        "description": "yaaa!",
        "durationday": "absent",
        "end": "10-04-2021 12:10:00",
        "id": 1,
        "location": "perth",
        "start": "10-04-2021 12:10:00",
        "title": "holiday",
    },
    {
        "description": "busy",
        "durationday": "fullday",
        "end": "10-22-2021 12:10:00",
        "id": 2,
        "location": "melbourne",
        "start": "10-19-2021 12:00:00",
        "title": "working",
    },
    {
        "description": "dd",
        "durationday": "halfday",
        "end": "10-24-2021 12:10:00",
        "id": 3,
        "location": "updated perth",
        "start": "10-24-2021 12:10:00",
        "title": "updated holiday",
    }
]

function YourComponent() {
    const [events, setEvents] = useState([])

    const getEvents = () => {
        // 直接使用硬编码数据,无需发起网络请求
        setEvents(eventList)
        console.log(eventList)
    }

    useEffect(() => {
        getEvents()
    }, []);

    // 后续渲染逻辑
    return <div></div>
}

场景2:需要从后端接口请求对应数据

将axios.get()的入参替换为后端提供的真实接口地址字符串即可,你写的硬编码数组可作为接口返回值的模拟参考,不能作为请求地址传入。参考代码如下:

import { useEffect } from 'react'
import axios from 'axios'

const getEvents = () => {
    // 替换为你的真实后端接口地址
    axios.get('https://你的后端接口地址/events')
        .then(response => {
            console.log(response.data)
        })
        .catch(err => console.log("This is error for fetching", err))
}

useEffect(() => {
    getEvents()
}, []);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 07:30:01