Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring and reordering Array with ES6 and React

I wanted to use a destructuring solution to reorder my array within my React container which it should be pretty straight forward. Given an array a1 = ['hello', 'hi', 'hola']

componentDidMount() {
  const { a1 } = this.props
  this.a2 = []
  [a2[2], a2[0], a2[1]] = a1  --> this line give an error!!
  console.log('new ordered array', a2) // ['hola', 'hello', 'hi'] --> this print properly my new array
}

If I try to console log or use it in render I got undefined The error I got at that line is:

Uncaught (in promise) TypeError: Cannot set property '#<Object>' of undefined

I really don't get it why I can print the value correctly in the console.log but when I try to actually use it in the code it doesn't work. It's maybe something React cycle related? I also tried to use it within my state but got the same error.

like image 956
Giorgia Sambrotta Avatar asked Jan 18 '26 10:01

Giorgia Sambrotta


2 Answers

This line gives you an error because this is one of those rare cases when automatic semicolon insertion lets you down. Never start new line with ( or [], otherwise interpreter considers it as continuation of the previous line and treats [ or ( as property access operation or function invocation.

This will work:

this.a2 = [];
[a2[2], a2[0], a2[1]] = a1

Or this:

this.a2 = []
;[a2[2], a2[0], a2[1]] = a1
like image 67
dfsq Avatar answered Jan 21 '26 02:01

dfsq


There is an . instead of , in this line [a2[2], a2[0]. a2[1]] = a1 --> this line give an error!!

like image 25
Saravanan I Avatar answered Jan 21 '26 00:01

Saravanan I