[英]How to properly destructure assignment with dynamic key? (react/destructuring-assignment)
I'm just getting an eslint error about destructuring this code, but I have no idea how it should look.我只是收到一个关于解构这段代码的 eslint 错误,但我不知道它应该是什么样子。 In this instance, I will probably just ignore this warning as this code is already pretty succinct, but, I am curious how it would be destructured.
在这种情况下,我可能会忽略这个警告,因为这段代码已经很简洁了,但是,我很好奇它会如何解构。 Any ideas or guidance is appreciated.
任何想法或指导表示赞赏。
_onChange = (e, key) => {
const edited = { ...this.state[key] }; <--- this line is throwing the eslint error
edited[e.name] = e.value;
this.setState({
[key]: edited,
});
};
so, I was able to get there with the comments.所以,我能够通过评论到达那里。
At the end of the day, I realized I just needed 'edited' to be an object containing the destructured object.在一天结束时,我意识到我只需要“编辑”成为一个包含解构对象的对象。
_onChange = (e, key) => {
const { [key]: { ...edited } } = this.state;
edited[e.name] = e.value;
this.setState({
[key]: edited,
});
};
Here, edited
will become { ...this.state[key] } which, after comparison, looks to be the same result as the previous code, but using the destructuring assignment.在这里,
edited
将变成 { ...this.state[key] } ,经过比较,它看起来与之前的代码结果相同,但使用了解构赋值。
I hope people will comment if they feel this is incorrect.我希望人们如果认为这是不正确的,请发表评论。
Even more simple, suggestion by Emile !更简单的是, Emile 的建议!
_onChange = (e, key) => {
const { [key]: current } = this.state;
this.setState({
[key]: { ...current, [e.name]: e.value },
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.