【问题标题】:How to solve Error Use object destructuring prefer-destructuring - React如何解决错误使用对象解构首选解构 - React
【发布时间】:2018-12-06 18:11:51
【问题描述】:

我遇到了一个我无法解决的丑陋问题。我是 React 的初学者。

这是我的代码

handleCheckChildElement(event) {
    let items = this.state.items;
    items.forEach(items = () => {
        if(items.value === event.target.value) {
            items.isChecked = event.target.checked;
        }
    });
    this.setState({ items });
}

这是错误的图像 -

【问题讨论】:

  • 请分享完整的组件代码以更好地了解问题

标签: reactjs


【解决方案1】:

在第 55 行使用下面的代码:

let {items}= {...this.state};

在此处阅读更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring

【讨论】:

  • 请稍候,错误已解决。我正在尝试运行该项目。
  • 我已经看到编译错误已解决,但让我在 Chrome/Firefox 中运行我的项目。请稍等,我一定会在短时间内将您的答案标记为正确
  • @Scooby 发生了什么?
【解决方案2】:

您的代码可以改进为如下所示。请在下面的代码中找到相关的cmets,以便您更好地理解

   handleCheckChildElement(event) {
           const { items } = this.state; //extract state values like this to a const variable 
           const newItems = items.map(item => { //do map on items because map returns a new array. It’s good practice to use .map than forEach in your case
                if(item.value === event.target.value) {
                         item.isChecked = event.target.checked;
                         return item; //return updated item object so that it will be pushed to the newItems array
                }
                return item; // return item because you need this item object as well
            });
           this.setState({ items: newItems}); //finally set newItems array into items
          }

【讨论】:

    【解决方案3】:
    handleCheckChildElement(event) {
       const items = this.state.items;
       const filtered = items.filter(item => item.value === event.target.value)
       .map(item => item.isChecked  = event.target.checked) ;
       this.setState({items : [...filtered] );
    }
    

    【讨论】:

    • 如果你能解释你改变了什么以及你为什么改变,那就太好了。顺便说一句,欢迎来到 SO!
    • 重量?!我写这个是为了演示。如何轻松过滤和更改它...在此示例中,我将现有数组替换为过滤结果
    • @David:即使您是在回答直接问题。但是,在提问者犯错的地方写一点解释总是很好的,你是如何解决的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 2018-09-28
    • 2022-07-04
    • 2016-11-02
    相关资源
    最近更新 更多