我可以在this.state路径中使用函数参数作为通配符吗? EX。 this.state。{参数}。价值

问题描述 投票:1回答:1

如何在路径中使用函数参数作为通配符?

addStorage函数应该将它收到的产品数量提高一个。如果我在路径中硬编码某些产品,它可以工作,但我不能在路径中使用“receivedKey”作为通配符。有可能做或者应该以其他方式做到吗?

到目前为止我已尝试过storage2。{receivedkey} .amount但它没有用。我尝试了使用括号和googled的所有可能变体,但到目前为止没有任何作用。

// Adds product to storage
addStorage = receivedKey => {
    const storage2 = this.state.storage;
    storage2.coffeemaker.amount = storage2.coffeemaker.amount + 1;
    this.setState({ storage: storage2 });
};
javascript reactjs
1个回答
1
投票

你可以使用[] bracket notation

// Adds product to storage
addStorage = receivedKey => {
    const storage2 = this.state.storage;
    storage2[receivedKey].amount = storage2[receivedKey].amount + 1;
    this.setState({ storage: storage2 });
};
© www.soinside.com 2019 - 2024. All rights reserved.