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

React JS中出现Cannot read property 'NaN' of undefined错误的修复求助

Fixing "Cannot read property 'NaN' of undefined" in React Price Calculations

Let's break down why you're hitting this error and how to fix it cleanly:

The Root Cause

Your data state starts off as undefined (or an empty array if you didn't explicitly initialize it) while your API call is still in flight. When you try to run those calculation lines before the API returns:

  • If data is undefined, data?.length returns undefined, so undefined - 1 becomes NaN. Trying to access data[NaN] gives you undefined, and then accessing .price on that throws the error you're seeing.
  • Even if data is an empty array, data.length - 1 equals -1, and data[-1] is also undefined—leading to the same broken property access.

Step-by-Step Fixes

1. Initialize data as an Empty Array

First, set a valid initial state for data to avoid early undefined-related issues:

const [data, setData] = useState([]); // Add this explicit initialization

2. Guard Against Insufficient Data

Before calculating your savings values, check that data has at least 2 elements (since you need both the first and last items to compute the savings). Here's how to adjust your calculation code:

// Initialize default values to avoid undefined variables
let saving = 0;
let percentageSaving = 0;

// Only run calculations if we have enough data points
if (data.length >= 2) {
  const latestPrice = data[data.length - 1].price;
  const initialPrice = data[0].price;

  const preSaving = latestPrice - initialPrice;
  saving = Math.round((preSaving + Number.EPSILON) * 100) / 100;

  const prePercentageSaving = ((1 - (initialPrice / latestPrice)) * 100);
  percentageSaving = Math.round((prePercentageSaving + Number.EPSILON) * 100) / 100;
}

3. Add Loading/Empty State Handling in JSX

To improve user experience and prevent broken renders, add checks before rendering content that depends on the calculated values:

if (isLoading) {
  return <div>Loading price data...</div>;
}

if (data.length < 2) {
  return <div>No price history available to calculate savings</div>;
}

// Now render your component with the valid calculated values
return (
  <div>
    <p>Total Saving: ${saving}</p>
    <p>Percentage Saved: {percentageSaving}%</p>
  </div>
);

Why This Works

By initializing data as an empty array, you eliminate the chance of dealing with undefined for the array itself. The length check ensures you only try to access array elements that actually exist, completely removing the NaN and undefined property access errors.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 15:02:43