简体   繁体   中英

How to unshift new value with existing array with spread operator?

I am trying to unshift an array value with existing array by using spread operator approach. getting error. any one help me to get correct approach?

here is my code :

uploadedFiles : [...state.uploadedFiles.unshift( (<fileActions.UploadFileSuccess>action).payload ) ]

getting an error as :

The Number is not array type

Thanks in advance.

Array#unshift returns the new length of the array.

You need just to take the item without spreading.

uploadedFiles: [(<fileActions.UploadFileSuccess>action).payload, ...state.uploadedFiles]

If you like to update state.uploadedFiles , you could unshift in advance.

state.uploadedFiles.unshift((<fileActions.UploadFileSuccess>action).payload);

uploadedFiles: [...state.uploadedFiles]

unshift mutates the array and returns the new length of the array, which is a number, and that can't be spreaded. Your code boils down to:

 [...state.uploadFiles.length]

Now to do that in an immutable and correct way, don't use unshift, just add the element to the array before spreading the previous version:

 [action.payload, ....state.uploadFiles]

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