说我state是这样的:
state
{ item:{ a:'a', b:'b' } }
然后,我可以通过以下操作a从项目中拉出:
a
const { a } = this.state.item
但能够以动态使用{}的es6?
{}
es6
例如const { variable } = this.state.item,where变量可以是a或b。
const { variable } = this.state.item
b
正如4castle指出的那样,您可以使用计算对象属性名称和结构分解以及附加的键/值对变量进行结构分解。
var object = { item: { a: 'a0', b: 'b0' } }, key = 'b', value; ({ [key]: value } = object.item); console.log(value);