admin管理员组文章数量:1296338
I'm from a C# background but am new to React and JS in general. I was wondering if there was a way to use lambda functions when declaring an array, for example:
this.state = {
arr: Array(9).fill( (i) => {<Foo index={i} />} ),
};
I'm trying to make an array of React.Components with ascending values in index, and was hoping this would be a viable option.
I'm from a C# background but am new to React and JS in general. I was wondering if there was a way to use lambda functions when declaring an array, for example:
this.state = {
arr: Array(9).fill( (i) => {<Foo index={i} />} ),
};
I'm trying to make an array of React.Components with ascending values in index, and was hoping this would be a viable option.
Share Improve this question asked Jun 2, 2018 at 17:46 Tom McKeownTom McKeown 1678 bronze badges 04 Answers
Reset to default 11Not with .fill()
alone, as it will just assign rather than invoke the function you give it.
Array(3).fill(() => {}); // [ function, function, function ]
You can use it along with .map()
, however, to acplish this. The iterator function you provide will be given the index as the 2nd argument (using _
as a throwaway variable for the 1st).
Array(9).fill(0).map((_, i) => <Foo index={i} />)
Using both is necessary because Array(9)
only assigns the array's length
, leaving the indexes unassigned.
'length' in Array(9) // true
0 in Array(9) // false
While .fill()
will work with unassigned indexes, .map()
specifically will ignore them.
You can also use Array.from()
instead, which accepts the same iterator as .map()
.
Array.from(Array(9), (_, i) => <Foo index={i} />)
Also, with it, the 1st argument doesn't necessarily have to be an Array
:
Array.from({ length: 9 }, (_, i) => <Foo index={i} />)
Probably something like this:
this.state = {
arr: new Array(5).map((emptyElement, index) => <Foo index={index} />);
}
Try:
this.state = {
arr: Array.from(Array(9), (value, index) => <Foo index={index} />)
}
You should not be adding ponents to the state, it's a good practice to put just serializable data in it. Also, ponents should be created inside render()
.
Anyway, if you wanted to do something similar to create, let's say, an array of numbers, I'd do something like this:
this.state = {
arr: Array(9).fill().map((v, i) => i),
};
Or, assuming those numbers always start at 0
:
this.state = {
arr: [...Array(9).keys()],
};
本文标签: javascriptIn reactJScan you use a loop in ArrayfillStack Overflow
版权声明:本文标题:javascript - In ReactJS, can you use a loop in Array.fill? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741619555a2388728.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论