Because this is a different array, we can now mutate it freely. It is different because it is stored in a different place in memory, however its contents are the same. This is a reference to a new array that is different than the array referenced by arr1. Now, arr3 makes a copy of the array by spreading its values into a new array. This would prevent components that rely on the state of this array from updating. If we mutate this array and pass it back, react might (I don't fully understand how this works under the hood) fail to detect a change because it sees that the reference to the array is unchanged. This means arr1 and arr2 reference the exact same array. ![]() In this example, the array is not assigned to arr2. Thanks a lot!Īrr1 holds a reference to an array. ![]() My question is, why is it acceptable to assign the value by writing 'nextList = "something"', but not acceptable to write something like "en = true"? What's the difference between the two? (quoted from the "Making other changes to an array" section of React official docs. This is a state mutation, which you should avoid!' So by changing en, you are also changing en. 'Although nextList and list are two different arrays, nextList and list point to the same object. 'Now that you have a copy, you can use mutating methods like nextList.reverse() or nextList.sort(), or even assign individual items with nextList = "something".' My second question is longer, so I'll quote the original words from the docs: ![]() ![]() I'm wondering why wouldn't that mutate the original array? ( )Ģ. In the "Making other changes to an array" section, it said that if we want to reverse an array, in order not to mutate the original array, we can firstly copy the array, and then use the "reverse()" method to with the new array. If that violates the community rules I'm really sorry, and I'll delete the post immediately. I'm not sure if it's appropriate to ask these kinds of questions here. Hi, I was reading the offical docs of React, and there were a few points about updating arrays that I couldn't understand.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |