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.
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
There is an . instead of , in this line [a2[2], a2[0]. a2[1]] = a1 --> this line give an error!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With