Whether the object destroys the work by reference or clones the object

I need to copy an object from this.stateto change some of its property values.

For example, in the following method, the state is mutated directly ( this.state.errors = {})

   authorFormIsValid = () => {
    var formIsValid = true;
    this.state.errors = {}; //clear any previous errors.

    if (this.state.author.firstName.length < 3) {
      this.state.errors.firstName = 'First name must be at least 3 characters.';
      formIsValid = false;
    }

    if (this.state.author.lastName.length < 3) {
      this.state.errors.lastName = 'Last name must be at least 3 characters.';
      formIsValid = false;
    }

    this.setState({errors: this.state.errors});
    return formIsValid;
  };

To avoid this, I know that we can use:

a) object distribution operator

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

b) Or Object.assign

let errors=Object.assign({},this.state.errors);

But sometimes it seems to me a few examples in which object destructuringit is used as follows:

authorFormIsValid = () => {
    let formIsValid = true;

   //Destructuring error and authors from this.state
    let {errors, author} = this.state;

    errors = {}; //clear any previous errors.

    if (author.firstName.length < 3) {
      errors.firstName = 'First name must be at least 3 characters.';
      formIsValid = false;
    }

    if (author.lastName.length < 3) {
      errors.lastName = 'Last name must be at least 3 characters.';
      formIsValid = false;
    }

    this.setState({errors});
    return formIsValid;
  };

So my question is: is it equivalent to the object destructuringother two methods mentioned above? I mean, can I avoid mutating the state directly using simple object destructuring?

+4
2

Object destructuring reference , , . ,

let {errors, author} = this.state;

errors = {}; //clear any previous errors.

.

.

let obj = {
  foo: {
    bar: 1
  }
}

let { foo } = obj;

console.log(foo.bar);      // 1
console.log(obj.foo.bar); // 1

foo.bar++;

console.log(foo.bar);      // 2
console.log(obj.foo.bar); // 2
Hide result
+4

. "this.state" .

let {errors, author} = this.state;

, error this.state

errors = {}; this.state. error . , - . error . - .

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

.

let errors = {};
0

Source: https://habr.com/ru/post/1678498/


All Articles