简体   繁体   English

如何在文字中创建动态对象?

[英]How can I create a dynamic object in a literal?

I have an object which includes several fields, most values are strings (constants) but I also want to use a variable (populated using some state)我有一个包含多个字段的对象,大多数值是字符串(常量),但我也想使用一个变量(使用某些状态填充)

const {order} = this.state;

myObject={{
    fieldA: 2,
    fieldB: ${order.value}
}}

I tried different variation of the above (with/without single quotes, etc.) but I am never able to set the value I need.我尝试了上述的不同变体(带/不带单引号等),但我永远无法设置我需要的值。

You are adding 2 brackets for an object which is not valid and no need of template literal.您正在为无效且不需要模板文字的对象添加 2 个括号。

const { order } = this.state;

const myObject = {
  fieldA: 2,
  fieldB: order.value,
};

If this.state looks like this:如果this.state看起来像这样:

this.state = {order: ""}

Declaring声明

const {order} = this.state

would just create a constant called order that is holding the value of this.state.order at the time order was declared.只会创建一个名为order的常量,它在声明order时保存this.state.order的值。 It will not be updated when this.state.order is updated. this.state.order更新时不会更新。

If you want to set myObject.fieldB to hold a reference to the value of this.state.order , that is, the state value of order, do this:如果要设置 myObject.fieldB 来保存对this.state.order的值的引用,即 order 的状态值,请执行以下操作:

const myObject = {
  fieldA: 2,
  fieldB: this.state.order,
}

You have used two braces (' {} ') which are not needed.您使用了两个不需要的大括号 (' {} ')。 The code should be like below代码应如下所示

const myobject = {fieldA: 2, fieldB: order.value};

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

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