如何解决错误使用对象分解优先分解-React

时间:2018-12-06 18:11:52

标签: reactjs

尊敬的Stack溢出成员。我陷入了一个无法解决的丑陋问题。我是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 });
}

这是错误的图片-Error Image

尊敬的Stack溢出成员,请帮助我解决这个丑陋的问题。我是React的新手。

3 个答案:

答案 0 :(得分:0)

在第55行使用以下代码:

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

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

答案 1 :(得分:0)

您的代码可以改进如下。请在下面的代码中找到相关的注释,以便您更好地了解

   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
          }

答案 2 :(得分:0)

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] );
}
相关问题