Replace array entry with spread syntax in one line of code?

前端 未结 6 771
情深已故
情深已故 2021-02-04 00:02

I\'m replacing an item in a react state array by using the ... spread syntax. This works:

let newImages = [...this.state.images]
newImages[4] = updatedImage
this         


        
6条回答
  •  有刺的猬
    2021-02-04 01:01

    Here is my self explaning non-one-liner

     const wantedIndex = 4;
     const oldArray = state.posts; // example
    
     const updated = {
         ...oldArray[wantedIndex], 
         read: !oldArray[wantedIndex].read // attributes to change...
     } 
    
     const before = oldArray.slice(0, wantedIndex); 
     const after = oldArray.slice(wantedIndex + 1);
    
     const menu = [
         ...before,  
         updated,
         ...after
     ]
    

提交回复
热议问题