更新折线图数据时遇Cannot read property 'dataSets' of undefined错误求助
Hey there! Let's get that chart update error sorted out for you. The Cannot read property 'dataSets' of undefined error is telling us that somewhere in your setState call, you're trying to access dataSets on a value that doesn't exist—specifically this.state.data.$set is coming up as undefined.
What's Wrong With Your Current Code?
Looking at your setState logic:
this.setState({ data: { ...this.state.data.$set, dataSets:[{ ...this.state.data.$set.dataSets[0], values }] }, xAxis: { ...this.state.xAxis.$set.valueFormatter, valueFormatter, axisMaximum, axisMaximum }, })
Three key issues here:
- You're referencing
this.state.data.$setandthis.state.xAxis.$set—but it's likely your initial state doesn't have a$setproperty nested insidedataorxAxis. That's why trying to access$set.dataSetsthrows the undefined error. - You're using
this.statedirectly in your setState update, which isn't safe because setState is asynchronous—you might be working with stale state values. - There's a duplicate
axisMaximumin your xAxis update, which is unnecessary.
The Corrected Approach
First, double-check your initial state has the right structure (this is probably what you already have, but confirm):
state = { data: { dataSets: [{ values: [], // Your initial values array // Any other dataSet properties like label, color, etc. }] }, xAxis: { valueFormatter: () => {}, // Your initial formatter function axisMaximum: 0 // Initial axis maximum value } };
Now update your setState to use the functional update pattern (which gives you the latest prevState), and directly modify the existing dataSets and xAxis properties without the non-existent $set:
this.setState(prevState => ({ data: { ...prevState.data, // Copy all existing properties in the data object dataSets: [ { ...prevState.data.dataSets[0], // Preserve existing properties of the first dataSet values: values // Replace with your new values array } ] }, xAxis: { ...prevState.xAxis, // Copy all existing xAxis properties valueFormatter: valueFormatter, // Update the formatter axisMaximum: axisMaximum // Update the max value (no duplicate!) } }));
Why This Works
- Using
prevStateensures you're always working with the most up-to-date state, avoiding bugs from setState's asynchronous behavior. - We're properly spreading the existing
dataandxAxisobjects to preserve properties we don't want to change, then overwriting only the parts we need to update. - We removed the non-existent
$setreferences, which was the root cause of your undefined error.
If you have multiple dataSets instead of just one, you could map over prevState.data.dataSets to update specific ones, but this code should fix your current issue!
内容的提问来源于stack exchange,提问作者HelenChen

