简体   繁体   中英

What are the ellipses (...) for in managing an event in React?

I'm a beginner in react, and I'm following a tutorial for display objects returned by a REST api. In handleChangeTitle method I get the value written in text box, and I update the state of component with new activeItem:

handleChangeTitle(e){
    //ogni volta che cambia qualcosa nella casella di testo, viene chiamata questa funzione
    var name = e.target.name
    var value = e.target.value 
    console.log('Name:', name)
    console.log('Value:', value)
    this.setState({
      activeItem:{
        ...this.state.activeItem,
        title:value
      }
    })
  }

What are the ellipsis for before referring to this.state.activeItem ?

It is called the spread syntax . It is a quick syntax to copy one object to another.

let obj1 = { a: 1 }
let obj2 = { ...obj1, b:2}
console.log(obj2)

Following code will print: {a:1,b:2}

Meaning content of obj1 was copied in obj2.

You can override values in new object as well, for eg:

let obj3 = {...obj2, b:3, c:2}
console.log(obj3)

This will print: {a:1,b:3,c:2} , the value of b was overridden.

You can follow this link for in-depth explanation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM