React JS中出现Cannot read property 'NaN' of undefined错误的修复求助
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
dataisundefined,data?.lengthreturnsundefined, soundefined - 1becomesNaN. Trying to accessdata[NaN]gives youundefined, and then accessing.priceon that throws the error you're seeing. - Even if
datais an empty array,data.length - 1equals-1, anddata[-1]is alsoundefined—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

