反应循环 [英] React for loops
问题描述
我正在学习JavaScript / React。我正在尝试为反应网站上的tic-tac-toe示例创建一个简单的for循环,但到目前为止它一直存在问题。奇怪的是,有几个地图示例,但没有循环示例。
I'm learning JavaScript / React. I'm trying to create a simple for loop for the tic-tac-toe example on the react website but so far its been problematic. Oddly, theres several map examples but no for loop examples.
无论如何,对于以下内容:
Anyway, for the following:
function Row(props){
function renderSquare (i) {
return <Square key={i} value={props.squares[i]} onClick={() => props.onClick(i)} />;
}
const columns = 3;
let ss = [];
for(var a = 0, i = props.counter * columns; a < 3; a++, i++){
//Test Code
}
return (
<div className="board-row">
{ss}
</div>
);
}
当我更换测试代码时,这可行
When I replace "Test Code", this works
ss.push(renderSquare(i));
但这失败
ss.push(<Square key={i} value={props.squares[i]} onClick={() => props.onClick(i)}/>);
第二个选项失败,因为它没有创建单独onClick元素。如何使失败的示例有效?
The second option fails since its not creating "separate" onClick elements. How can I make the failing example work?
更新#1
更新#2
我按照@Matthias247的建议更改了var,现在可以使用:D
Update #2 I changed the var to let as recommended by @Matthias247 and it now works :D
function Row(props){
function renderSquare (i) {
return <Square key={i} value={props.squares[i]} onClick={() => props.onClick(i)} />;
}
const columns = 3;
let ss = [];
for(let a = 0, i = props.counter * columns; a < columns; a++, i++){
ss.push(<Square key={i} value={props.squares[i]} onClick={() => props.onClick(i)}/>);
//ss.push(renderSquare(i));
//console.log(i);
}
return (
<div className="board-row">
{ss}
</div>
);
}
推荐答案
我认为问题在于您将 i
捕获到元素中,并将 onClick
关闭。您在for循环期间更改了 i
,但最后它对所有插入的元素都相同 - > props.counter + 3
。
I think the problem is that you capture i
into the element and the onClick
closure. You change i
during the for loop, but in the end it's the same for all inserted elements -> props.counter + 3
.
要修复它,您需要为每个元素创建所有捕获值的唯一实例。这正是你用 renderSquare
方法做的,它在函数体内创建了一个 i
的新实例,这是现在由元素捕获。
To fix it you need to create a unique instance of all captured values for each element. This is exactly what you do with the renderSquare
method which creates a new instance of i
inside the function body, which is now captured by the element.
编辑:
使用让
binding,每次迭代创建一个新的变量实例,也可以:
Using a let
binding, which creates a fresh instance of the variable per iteration, also works:
for (let a = 0, i = props.counter; a < 3; a++, i++) {
ss.push(<Square key={i} value={props.squares[i]} onClick={() => props.onClick(i)}/>);
}
这篇关于反应循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!