简体   繁体   中英

Can somebody help me in understanding what is happening in this piece of code

I am not able to follow the set state method in this piece of code.

    locked: Array(5).fill(false), ///<<<  THIS IS THE INITIAL STATE

     this.setState(st => ({   //<<<<<  SETTING THE STATE ON BUTTON CLICK
      locked: [
        ...st.locked.slice(0, idx),
        !st.locked[idx], // << Iam not able to follow this line and the line after it.
        ...st.locked.slice(idx + 1)
      ]

It just negates the item at idx position.

How does it do it??

First it copies all the elements before idx from locked and pastes it back inside locked with below line.

this.setState(st => ({ 
   locked: [ ...st.locked.slice(0, idx)]
}));

And then it negates the item at idx position.

!st.locked[idx]

And then copies rest of the items back in array.

...st.locked.slice(idx + 1)

locked is an array of booleans. This code makes use of the spread syntax to create a new array of booleans from the current one but with one element at idx inverted. Detailed breakdown:

this.setState(st => ({              // callback version of setState that receives the current state as the argument
    locked: [                       // set a new array for `locked` that consists of :
        ...st.locked.slice(0, idx), // every element before the element at idx
        !st.locked[idx],            // the element at idx but inverted
        ...st.locked.slice(idx + 1) // every element after idx
    ]

You could also create a copy of the original array and invert the element at idx after that:

this.setState(st => {
    const locked = Array.from(st.locked);
    locked[idx] = !locked[idx];
    return {locked};
});

Or you could map over the array:

this.setState(st => ({
    locked: st.locked.map((item, i) => i === idx ? !item : item)
}));

All of those solve the problem of inverting the element at idx while creating a new array (react state must not be mutated).

//locked is a state property with an array value of 5 false booleans
locked: Array(5).fill(false)

//passing current state through a function
this.setState(st => ({ 
  //selecting locked property of state to update
  locked: [
    //making a copy of all indexes up to the index that is to be updated
    ...st.locked.slice(0, idx),
    //toggling the selected index to have a value of true (if previously false)
    !st.locked[idx], 
    //making a copy of all indexes after the index that is to be updated
    ...st.locked.slice(idx + 1)
    ]
}))

It doesn't make complete sense without understanding where idx is coming from. But it takes everything in the st.locked array and leaves it the same, except for idx , which it inverts.

Then it returns a new array with those elements, which must have been done intentionally. Otherwise it would be much more trivial to target st.locked[idx]. There is some reason the author of this code is returning a new array and it's probably important.

Hello I Tried This On This piece of code and now I am clear about it.

    const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
    console.log(animals.slice(0, 2));
    console.log(animals[2] = "New Item Bro")
    console.log(animals.slice(2  + 1));
    console.log(animals) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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