[英]How can I create a dynamic object in a literal?
我有一個包含多個字段的對象,大多數值是字符串(常量),但我也想使用一個變量(使用某些狀態填充)
const {order} = this.state;
myObject={{
fieldA: 2,
fieldB: ${order.value}
}}
我嘗試了上述的不同變體(帶/不帶單引號等),但我永遠無法設置我需要的值。
您正在為無效且不需要模板文字的對象添加 2 個括號。
const { order } = this.state;
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
的值的引用,即 order 的狀態值,請執行以下操作:
const myObject = {
fieldA: 2,
fieldB: this.state.order,
}
您使用了兩個不需要的大括號 (' {}
')。 代碼應如下所示
const myobject = {fieldA: 2, fieldB: order.value};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.