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

Nivo Line Charts报TypeError: n7.filter is not a function,疑因数据格式不符

解决Nivo Line Chart数据格式不匹配导致的TypeError问题

问题背景

使用REST API拉取数据用于Nivo Line Charts组件,组件要求的数据格式为:

Array<{
    id:   string | number
    data: Array<{
        x: number | string | Date
        y: number | string | Date
    }>
}>

但API返回的是单个对象:

{
    "id": 286,
    "data": [
        {
            "x": "2024-08-13",
            "y": 5828
        },
        {
            "x": "2024-08-14",
            "y": 5829
        }
    ]
}

当前获取数据的代码如下:

const [chart, setChart] = useState([]);

let {id} = useParams();

let config = {
    headers: {
        'Content-Type': 'application/json',
    }
}

useEffect(() => {
    axios.get(`http://localhost:8000/api/stock/chart/${id}`, config)
        .then(response => {
            setChart(response.data);
        }).catch(error => {
            console.log(error);
    })
}, [])

运行后抛出错误:

TypeError: n7.filter is not a function

原因分析

Nivo Line Chart要求传入数组类型的数据源,但API返回的是单个对象。直接将该对象赋值给初始为数组的chart状态后,组件接收到的是对象而非数组,而对象不存在数组的filter方法,因此触发类型错误。

解决方案

将API返回的单个对象包装成数组,再赋值给chart状态。

修改后的代码:

const [chart, setChart] = useState([]);

let {id} = useParams();

let config = {
    headers: {
        'Content-Type': 'application/json',
    }
}

useEffect(() => {
    axios.get(`http://localhost:8000/api/stock/chart/${id}`, config)
        .then(response => {
            // 将单个对象包装为数组
            setChart([response.data]);
        }).catch(error => {
            console.log(error);
    })
}, [])

这样处理后,chart状态就符合Nivo Line Chart要求的数组格式,组件可以正常调用filter方法渲染图表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 14:36:04