map method iteration in stepper for material ui

孤街浪徒 提交于 2019-12-02 09:34:17

Here is a working codesandbox: https://codesandbox.io/s/6l3wpo3xyr

To me, it seems that is working properly and with clear code. It can be done a bit better but to start with, it may be ok.

I can edit the answer to add details if needed.

Answer for comment about Object.entries

As an instance variable for the component I declared:

steps = {
  "Select campaign settings": Step1,
  "Create an ad group": Step2,
  "Create an ad": Step3
};

This is just a Plain Javascript Object. In ES6 the Object class has the entries method that, taken an object like this one, returns an array an array of key and values of the given object. In this case:

Object.entries(steps)

[
  [ "Select campaign settings", Step1 ],
  [ "Create an ad group", Step2 ],
  [ "Create an ad", Step3 ]
]

Having such a structure, it's easier to map through the key-value pairs with map. The first argument of the map method of the Array class is the current element of the array. Having used Object.entries earlier, the element is the single array that represents a key-pair:

Object.entries(steps)[0]  // [ "Select campaign settings", Step1 ]

Answer for comment about .map(([ label, CustomStep ]) => ...

This is just a common use of the Array.map method. Generally, it allows to transform an array into another using a mapping function. A function that takes an element of the array and return another thing.

In this case, the element of the array to cycle is the key-value pair provided by the Object.entries call. With ES6 arrays, as well as objects, can be destructured, and that is what is happening there:

// you may see something like this around:
.map(element => {
  // let's say that element is an array, you'll use it like:
  // element[0] is the first element
  // element[1] is the second one
})

// with ES6 that array can be destructed on-the-fly this way, which is totally equivalent
.map(([ label, CustomStep ]) => {
  // label is the index 0 (element[0])
  // CustomStep is the index 1 (element[1])
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!