简体   繁体   English

解构和克隆 object / 一行?

[英]Destructuring and clone object / One line?

I'm using react.js , and I want to obtain from the state an array, but I required to clone it and save it into a const .我正在使用react.js ,我想从 state 获取一个数组,但我需要克隆它并将其保存到const中。 I can do it with two lines of code;我可以用两行代码来完成; exists a way to do it in a single line of code?有没有办法在一行代码中做到这一点?

Example:例子:

const { data } = this.state
const newData = [...data]

FYI, I'm using eslint, and with "parser": "babel-eslint" config and VSC show me a warning if I'm trying to do this:仅供参考,我正在使用 eslint,如果我尝试这样做,则使用"parser": "babel-eslint"配置和 VSC 会向我显示警告:

const data = [...this.state.data]

Warning message: Must use destructuring state assignments - lint react / destructuring-assignment警告消息: Must use destructuring state assignments - lint react / destructuring-assignment

I don't want to remove/customize the rules of eslint... but I don't want to extend the code more than necessary.我不想删除/自定义 eslint 的规则......但我不想过度扩展代码。

Any suggestion?有什么建议吗?

Here's how you can create an Array slice of this.state.data through destructuring all in one line:以下是如何通过在一行中解构所有内容来创建this.state.data的数组切片:

const { data: [...newData] } = this.state

Caveat, this is not a deep clone if you're expecting that.警告,如果你期待的话,这不是一个深度克隆。 It's just a new Array referencing the original Array items.它只是一个引用原始数组项的新数组。

Note that I think your eslint rules are insane to require using destructuring.请注意,我认为您的 eslint 规则要求使用解构是疯狂的。 It's not always the best solution.这并不总是最好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM