简体   繁体   English

这两个处理 state 的函数之间的区别

[英]Difference between these two functions that handle the state

I tried these two functions and I thought they do the same thing, but apparently no.我尝试了这两个功能,我认为它们做同样的事情,但显然不是。

The first Function:第一个Function:

    setEatenFoodList(prevList => {
      const newList = [];
      for (let i=0 ; i<prevList.length ; i++) {
        if (i === index){
          const editedFood = prevList[i];
          editedFood.removingFade = true;
          newList.push(editedFood)
        } else {
          newList.push(prevList[i])
        }
      }
      return newList;
    })

The second Function:第二个Function:

    setEatenFoodList(prevList => {
      prevList[index].removingFade = true;
      return prevList;
    })

I don't see the difference?我没看出区别?

The first code creates a new list called "newList" and iterates through the elements of the original list "prevList" and adds them to the new list.第一个代码创建一个名为“newList”的新列表,并遍历原始列表“prevList”的元素并将它们添加到新列表中。 If the current index of the loop is equal to the variable "index", it creates a new variable called "editedFood" which is a copy of the element at that index, sets the "removingFade" property of "editedFood" to true and pushes it to the "newList".如果循环的当前索引等于变量“index”,它会创建一个名为“editedFood”的新变量,它是该索引处元素的副本,将“editedFood”的“removingFade”属性设置为 true 并推送它到“newList”。 Finally, it returns the "newList" as the output.最后,它返回“newList”作为 output。

The second code is simpler, it directly modifies the "prevList" by setting the "removingFade" property of the element at index "index" to true.第二个代码更简单,它通过将索引“index”处元素的“removingFade”属性设置为 true 来直接修改“prevList”。 And it returns the original list "prevList" as output.并将原始列表“prevList”返回为 output。

The main difference between the two codes is that the first one creates a new list, whereas the second one modifies the original list.两个代码之间的主要区别在于第一个代码创建一个新列表,而第二个代码修改原始列表。

More simply: the first function iterates through all the elements of newList and pushes everything inside the newList.更简单地说:第一个 function 遍历 newList 的所有元素并将所有内容压入 newList 中。 The second function pushes everything into the original list (prevList)第二个 function 将所有内容推入原始列表(prevList)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM