React组件中test函数嵌套循环未执行问题排查与修复求助
Hey there! Let's dig into your problem—this isn't actually an async issue, it's some straightforward bugs in your loop logic that are keeping the inner code from running. Let's break it down step by step:
1. Broken Outer Loop Condition
Look at your test function's outer loop:
for(var i=0; j < this.state.data.length;i++){
You're using j in the condition before it's even declared! Plus, you meant to check i < this.state.data.length here, not j. Since j is undefined initially, undefined < number evaluates to false, so the loop never starts at all. That's why none of your inner console logs or logic run.
2. Callback Passing Mistake
When you call this.test(console.log(dateArray)), you're immediately executing console.log(dateArray) right then (before test even runs) and passing its return value (undefined) as the callback. You need to wrap it in an arrow function to pass the actual callback:
this.test(() => console.log(dateArray));
3. Variable Hoisting Issues with var
Using var for i and j causes variable hoisting—your inner j will overwrite the outer one (though in this case the loop never runs, it's still a bug waiting to happen). Switch to let or const for block-scoped variables to avoid this.
4. Bonus: Global Variables Are a Bad Idea in React
You're using global variables like gData, dateArray—these won't trigger React's re-rendering when they change, which will lead to your chart not updating correctly. Move these into your component's state instead.
Fixed Version of the test Function
Here's the corrected test function with all these fixes:
test=(callback)=>{ // Use let for block-scoped variables for(let i=0; i < this.state.data.length;i++){ console.log(i); let yearTotal = parseInt(this.state.data[i].time); let yearA = this.state.data[i].date.substr(0,4); for(let j=0; j < this.state.data.length;j++){ let yearB = this.state.data[j].date.substr(0,4); if(yearA === yearB && i !== j){ yearTotal += parseInt(this.state.data[j].time); // Make sure to parse this too! } console.log("Marker, which doesn't show up"); } const yearArray = [yearA, yearTotal]; dateArray.push(yearArray); if(i === this.state.data.length - 1){ callback(); } } }
Extra Optimization: Avoid Nested Loops
Right now your code uses an O(n²) nested loop to sum yearly totals. You can simplify this with Array.reduce to make it cleaner and faster:
test=(callback)=>{ const yearlyTotals = this.state.data.reduce((acc, item) => { const year = item.date.substr(0,4); const time = parseInt(item.time); acc[year] = (acc[year] || 0) + time; return acc; }, {}); // Convert the object to your desired array format dateArray = Object.entries(yearlyTotals); callback(); }
One More Thing: Fix setGraph
Your setGraph function has console.log(dateArray) after the break statement in the year case—this log will never run. Move it inside the case before the break.
内容的提问来源于stack exchange,提问作者SweetFeet

