功能句柄保存
@bind
private handleSave() {
const { coin, balance } = this.state;
console.log('coin', coin);
console.log('balance', balance);
const updatedCoin = Object.assign({
...coin,
position: balance
}, coin);
console.log('updatedCoin', updatedCoin);
this.props.updateCoinPortfolio(updatedCoin);
this.props.toggle(false);
}
在第一个控制台上,日志coin
是以下对象:
{
availableSupply: "17572412",
currency: "BTC",
exchange: "",
exchange_base: "",
marketCap: 67651096742.34,
name: "Bitcoin",
percentage: 100,
position: 1,
price: "3849.84695",
value: 3849.84695
}
还有balance = 2
此日志中的下一个:console.log('updatedCoin', updatedCoin);
我希望硬币的位置现在为2
,而不是1
。但这仍然是1
吗?
Object.assign部分:
const updatedCoin = Object.assign({
...coin,
position: balance
}, coin);
答案 0 :(得分:2)
您正在混合隐喻。您都要assign
:
const updatedCoin = Object.assign({}, coin, {position: balance});
或属性传播:
const updatedCoin = {
...coin,
position: balance
};
您的assign
代码不起作用,因为您将coin
放在了更新的对象之后,因此position
被coin
覆盖了。 (通过assign
-和传播-这是最后一个获胜的游戏。)
答案 1 :(得分:2)
您需要这样做:
const UpdatedCoin = Object.assign({... coin,position:balance},{});
或更简单:
constupdatedCoin = {...硬币,位置:余额}
答案 2 :(得分:1)
您需要以这种方式使用它才能使其正常工作:
const updatedCoin = Object.assign({}, coin, {position: balance});
使用方式,首先要生成一个带有原始硬币对象和更新位置的对象。这样就足以获取更新的对象,如下面的示例所示:
let coin = {
availableSupply: "17572412",
currency: "BTC",
exchange: "",
exchange_base: "",
marketCap: 67651096742.34,
name: "Bitcoin",
percentage: 100,
position: 1,
price: "3849.84695",
value: 3849.84695
}
console.log({...coin, position: 2});
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
但是最后,您最终将所有原始钱币属性分配回了更新的对象,从而获取了起始对象:
let coin = {
availableSupply: "17572412",
currency: "BTC",
exchange: "",
exchange_base: "",
marketCap: 67651096742.34,
name: "Bitcoin",
percentage: 100,
position: 1,
price: "3849.84695",
value: 3849.84695
}
let updated = {...coin, position: 2};
console.log(Object.assign(updated, coin));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
答案 3 :(得分:1)
只需:
const updatedCoin = {
...coin,
position: balance
}
使用您的代码,您首先将coin
与{position: balance}
合并,然后与assign
合并,您的{position: balance}
被coin
的值覆盖为position
。