为什么我在 React 中的对象显示未定义的对象值?

Why is my object in React showing an undefined Object value?

这是我的 React 组件:

const ChartItem = ({ id, apiUrl }) => {
    const [nivoChartData, setNivoChartData] = useState([]);

    //

    //declare the API call
    const apiCallAndConversionForNivoFormat = useCallback(async () => {
        try {
            const response = await axios.get(apiUrl);
            console.log("response: ");
            console.log(response);

            //converting api response into the format needed by nivo charts
            const dataConvertedForNivo = [
                {
                    id: response.data.symbol,
                    color: "hsl(90, 70%, 50%)",
                    data: response.data.historical.forEach((key) => {
                        key["x"] = key["date"];
                        key["y"] = key["close"];
                        delete key["date"];
                        delete key["close"];
                    }),
                },
            ];
            console.log("dataConvertedForNivo: ");
            console.log(dataConvertedForNivo);

            setNivoChartData(dataConvertedForNivo);
        } catch (e) {
            console.error(e);
        }
    }, [setNivoChartData, apiUrl]);

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

    return (
        <div className="chart-item">
            <NivoLineChart key={id} nivoData={nivoChartData} />
        </div>
    );
};

日志:

修改前的原API响应格式:

{
    "symbol": "AAPL",
    "historical": [
        {
            "date": "2021-02-24",
            "close": 125.349998
        },
        {
            "date": "2021-02-23",
            "close": 125.860001
        },
        {
            "date": "2021-02-22",
            "close": 126
        },
    ]
}

^ 我相信 response 日志现在显示的是“x”和“y”,而不是“日期”和“关闭”,这是由于记忆。

我需要转换为的 nivo 图表示例格式:

[
  {
    "id": "AAPL",
    "color": "hsl(90, 70%, 50%)",
    "data": [
      {
        "x": "2021-02-24",
        "y": 125.349998
      },
      {
        "x": "2021-02-23",
        "y": 125.860001
      },
      {
        "x": "2021-02-22",
        "y": 126
      },
    ]
  }
]

谁能理解为什么 dataConvertedForNivo.data 是未定义的?有没有更好的方法来进行这种响应转换?

您需要将 forEach 替换为 map

const dataConvertedForNivo = [
    {
        id: response.data.symbol,
        color: "hsl(90, 70%, 50%)",
        data: response.data.historical.map(key => {
            key["x"] = key["date"];
            key["y"] = key["close"];
            delete key["date"];
            delete key["close"];
            return key;
        }),
    },
];