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 0
Add a ment  | 

4 Answers 4

Reset to default 11

Not 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