简体   繁体   English

如何使用动态键正确解构赋值? (反应/解构分配)

[英]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.

相关问题 对Eslint进行销毁分配 - React Eslint destructuring-assignment 如何修复 eslint: react/destructuring-assignment 错误? - How can I fix eslint: react/destructuring-assignment error? 考虑反应/解构分配定义 state 子数组的最佳方法 - Best way to define a subarray of state with consideration of react/destructuring-assignment 不能使用 this.state 因为我使用 eslint,“必须使用解构状态赋值”/解构赋值反应 - can't using this.state because i use eslint, “Must use destructuring state assignment” /destructuring-assignment react 是否可以在 function 中使用道具作为默认值(使用反应/解构分配规则时) - Is it possible to use props as a default value in a function (when using react/destructuring-assignment rule) React 或 nodejs 中的解构赋值 - Destructuring assignment in React or nodejs “必须使用解构状态赋值”:如何从对象中解构并放置在对象字面量内的属性上 - "Must use destructuring state assignment": How to destructure from object and place on property inside object literal javascript中解构赋值中的逻辑赋值如何实现? - How to implement the logical assignment in destructuring assignment in javascript? 如何通过销毁分配将数据绑定到此? - how to bind data to this by destructuring assignment? 如何导出部分解构赋值? - How to export a part of destructuring assignment?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM