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

React JS中TypeError: Cannot read properties of undefined问题求助

问题解决:修正你的数据转换函数

你的代码核心问题是循环条件错误,导致只处理了q1和p1,没覆盖到q1到q5、p1到p5的所有数据。

错误原因

原循环里的i < 1 + 1等价于i < 2,循环只会执行1次(i=1),自然无法生成包含5组数据的数组。

修正后的代码

直接修改循环条件,让i从1遍历到5:

const myfunction = (data) => {
    console.log(data);
    const myData = [];
    // 修正循环条件,i从1到5
    for (let i = 1; i <= 5; i += 1) {
      const obj = {};
      obj.price = data['q' + i];
      obj.vol = data['p' + i];
      myData.push(obj);
    }
    return {
      name: 'ss',
      color: '#ffff',
      data: myData,
    };
};

更简洁的函数式写法(可选)

如果想更符合React常用的函数式风格,可以用Array.from生成遍历范围,再用map转换:

const myfunction = (data) => {
    console.log(data);
    // 生成1到5的数字数组,再映射成目标对象
    const myData = Array.from({ length: 5 }, (_, index) => {
        const i = index + 1;
        return {
            price: data[`q${i}`],
            vol: data[`p${i}`]
        };
    });
    return {
        name: 'ss',
        color: '#ffff',
        data: myData,
    };
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:51:29