Reputation: 759
I have a for loop that needs to render div
s according to some logic:
let allRecords;
if (this.state.allRecords) {
allRecords = (() => {
let paramOne = this.state.paramOne;
let paramTwo = this.state.paramTwo;
let paramThree = this.state.paramThree;
let paramFour = this.state.paramFour;
let paramFive = this.state.paramFive;
let paramSix = this.state.paramSix;
for (let i = 0; i < this.state.length; i++) {
let res;
res = (
<div>
<div className="event-result-table-container">
<div className="result-cell">{paramOne[i]}</div>
<div className="result-cell">
<span>{paramTwo[i] ? "Win" : "Lose"}</span>
</div>
<div className="result-cell">{paramThree[i]}</div>
<div className="result-cell">{paramFour[i]}</div>
<div className="result-cell">{paramFive[i]}</div>
<div className="result-cell-last">{paramSix[i]}</div>
</div>
</div>
);
return res;
}
})();
}
The six param
arrays all have a similar structure. For example, I have copied the paramSix
state array from the Chrome console, and it looks like this:
[
[
479,
480,
481,
482,
483,
484,
485,
486,
487
]
]
Expected Result: I want to see a bunch of res
blocks rendered (equal to this.state.length
), each with its correct value taken from the state arrays.
Observed result: Only one row of blocks gets rendered, but all the values are there (checked with React DevTools), as if it renders only one block of div
s, but puts all the values in their cells, instead of putting them in separate blocks.
What am I doing wrong here?
Upvotes: 0
Views: 44
Reputation: 5686
The first time you call return
in your function it stops executing and returns that value. You're calling it within the for
loop, but it doesn't matter because for
loops don't work that way, they aren't functions. So the loop doesn't run more than once.
The other issue that you have is that your data, like paramSix
that you have showed us, is an array with an array of data, so when you reference paramSix[i]
in the first (and only) execution of the loop, you are referencing an array, not a number. Instead you probably want paramSix[0][i]
.
Here's a way to rewrite it so that an array of elements is created. Please note that I used object destructuring to simplify getting the params from the state, and used const
since these values shouldn't be changed here:
let allRecords = [];
if (this.state.allRecords) {
const {
paramOne,
paramTwo,
paramThree,
paramFour,
paramFive,
paramSix
} = this.state;
for (let i = 0; i < this.state.length; i++) {
allRecords.push(
<div>
<div className="event-result-table-container">
<div className="result-cell">{paramOne[0][i]}</div>
<div className="result-cell">
<span>{paramTwo[0][i] ? "Win" : "Lose"}</span>
</div>
<div className="result-cell">{paramThree[0][i]}</div>
<div className="result-cell">{paramFour[0][i]}</div>
<div className="result-cell">{paramFive[0][i]}</div>
<div className="result-cell-last">{paramSix[0][i]}</div>
</div>
</div>
);
}
}
Upvotes: 2