[英]Using Object.keys(), map(), …Array(), reduce() and concat() in a single const
I'm learning React.js on Udemy.我正在 Udemy 上学习 React.js。 We wrote a long stateless component which used Object.keys()
, map()
, ...Array
, reduce()
and concat()
in a single const.我们编写了一个长的无状态组件,它在单个 const 中使用Object.keys()
、 map()
、 ...Array
、 reduce()
和concat()
。
I know every method we used in this stateless component.我知道我们在这个无状态组件中使用的每一种方法。 But when I used them all in a single component I lost a track.但是当我在一个组件中使用它们时,我丢失了一条轨道。
Like why did we put []
on reduce()
method as second parameter or what does (_, i)
is for on map()
method?就像我们为什么将[]
放在reduce()
方法上作为第二个参数,或者(_, i)
用于map()
方法是什么?
Can you explain this code step by step?你能一步一步解释这段代码吗?
const burger = (props) => {
let transformedIngredients = Object.keys( props.ingredients )
.map( igKey => {
return [...Array( props.ingredients[igKey] )].map( (_, i) => {
return <BurgerIngredient key={igKey + i} type={igKey} />;
});
})
.reduce((arr, el) => {
return arr.concat(el);
}, []);
Object.keys( props.ingredients )
retrieves an array of ingredients names.检索一组成分名称。
.map( igKey => {
maps that array to a new array, were each element contains将该数组映射到一个新数组,每个元素是否包含
[...Array( props.ingredients[igKey] )]
an array that has as many entries as the value related to the ingredient in the passed object.一个数组,其条目数与传递的 object 中的成分相关的值一样多。
.map( (_, i) => {
then maps that inner array, ignores the value (which is undefined
for an empty array anyways) and only takes the index and maps it to然后映射该内部数组,忽略该值(无论如何对于空数组都是undefined
的)并且只获取索引并将其映射到
<BurgerIngredient key={igKey + i} type={igKey} />;
Now we do have a 2D array of BurgerIngredients, and现在我们确实有一个 BurgerIngredients 的二维数组,并且
.reduce((arr, el) => {
return arr.concat(el);
}, []);
flattens that to an array of BurgerIngredients.将其展平为一系列 BurgerIngredients。 Reducing means that we start with the initial value ( []
) and .concat
every value (inner array) of the original array to it.归约意味着我们从初始值( []
)和.concat
原始数组的每个值(内部数组)开始。
I'd write that as:我会这样写:
const Burger = ({ ingredients }) => {
const list = [];
for(const [ingredient, amount] of Object.entries(ingredients)) {
for(let count = 0; count < amount; count++) {
list.push(<BurgerIngredient key={ingredient + count} type={ingredient} />);
}
}
return <div className="burger">
Ingredients:
{list}
</div>;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.