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

How can I create a dynamic object in a literal?

我有一个包含多个字段的对象,大多数值是字符串(常量),但我也想使用一个变量(使用某种状态填充)

const {order} = this.state;

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

我尝试了上述的不同变体(with/without 单引号等),但我永远无法设置我需要的值。

您正在为无效且不需要模板文字的对象添加 2 个括号。

const { order } = this.state;

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

您使用了两个不需要的大括号 ('{}')。代码应该如下所示

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

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

this.state = {order: ""}

声明中

const {order} = this.state

只会创建一个名为 order 的常量,它在声明 order 时保存 this.state.order 的值。 this.state.order 更新后不会 更新。

如果要设置myObject.fieldB持有对this.state.order值的引用,即订单的状态值,这样做:

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