在退货声明中进行ES6解构 [英] ES6 destructuring within a return statement
本文介绍了在退货声明中进行ES6解构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在同时返回对象时对其进行解构。
例如,要更改此代码:
Is it possible to destructure an object while returning it at the same time. For example, to change this code:
const mapStateToProps = ({ newItem }) =>{
const { id, name, price } = newItem;
return { id, name, price };
}
对于这样的事情:
const mapStateToProps = ({ newItem }) =>{
return { id, name, price } = newItem;
}
推荐答案
不,这是不可能的。
(免责声明:您的语法有效并且同时进行解构和返回,但它相当于
({ id, name, price } = newItem); // assigns global variables
return newItem;
这可能不是你想要的)
要做什么你想要(我假设是创建一个新对象),你需要使用对象文字(可能使用简写属性表示法)。另请参阅使用ES 6中的对象获取某些属性的单行程序:
To do what you want (which I assume is creating a new object), you need to use an object literal (potentially with shorthand property notation). See also One-liner to take some properties from object in ES 6:
const mapStateToProps = ({newItem: {id, name, price}}) => ({id, name, price});
这篇关于在退货声明中进行ES6解构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文