【问题标题】:Destructuring and reordering Array with ES6 and React使用 ES6 和 React 解构和重新排序数组
【发布时间】:2018-01-25 17:11:56
【问题描述】:

我想使用解构解决方案在我的 React 容器中重新排序我的数组,这应该非常简单。 给定一个数组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
}

如果我尝试控制台日志或在渲染中使用它,我得到undefined 我在该行得到的错误是:

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

我真的不明白为什么我可以在console.log 中正确打印该值,但是当我尝试在代码中实际使用它时它不起作用。 这可能与 React 循环有关? 我也尝试在我的州内使用它,但遇到了同样的错误。

【问题讨论】:

  • 看看有错误的那一行,你有一个点(.)应该是逗号
  • 这叫解构,不是解构。
  • 感谢@PeterMader

标签: javascript arrays reactjs ecmascript-6


【解决方案1】:

这一行给你一个错误,因为这是自动分号插入让你失望的极少数情况之一。切勿以([] 开始新行,否则解释器将其视为上一行的延续,并将[( 视为属性访问操作或函数调用。

这将起作用:

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

或者这个:

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

【讨论】:

  • 事情就是这样!问题是“我的 lint 不允许我添加分号 -.- 前端开发,非常有趣:) 无论如何我已经用另一种方式解决了,但至少现在我知道了,谢谢!
【解决方案2】:

[a2[2], a2[0]. a2[1]] = a1 --> this line give an error!! 这一行中有一个. 而不是,

【讨论】:

  • 你是对的,但我只是在这里打错了问题,在我的实际代码中,有一个逗号
猜你喜欢
  • 2017-07-09
  • 2020-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
相关资源
最近更新 更多