How to solve Error Use object destructuring prefer

2019-08-01 12:30发布

Dear Stack overflow members. I am stuck with an ugly issue which I am unable to resolve. I am beginner in React.

This is my Code

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

This is the image of the error - Error Image

Dear Stack overflow members please help me to solve this ugly issue. I am beginner in React.

标签: reactjs
3条回答
祖国的老花朵
3楼-- · 2019-08-01 12:47

Your code can be improved to something like below. Please find relevant comments in the code below for your better understanding

   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
          }
查看更多
Deceive 欺骗
4楼-- · 2019-08-01 12:55
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] );
}
查看更多
登录 后发表回答