user10516706
user10516706

Reputation:

ES6 destructuring assignment outside of constructor

I'm developing a project based on react and I'm using ES6 and babel transpile tools and plugins. I know about destructuring assignment inside constructor of class, it is like below:

~~~
constructor(props){
  super(props);

  ({
    name: this.name,
    family: this.family
  } = props);
}
~~~

The above code is instead of this.name = props.name; and this.family = props.family;.

But I don't use constructor because I used babel-plugin-transform-class-properties and I don't need to have constructor, this.state and binding this to every class functions. I just declare state and declare functions as arrow function, see following sample:

class Sample extends React.PureComponent {
  state = {
    ~~~
  };

  handleSample = () => { ~~~ };

  ~~~
}

But now I don't know how I can destructuring my this.props outside of constructor inside body of class, and add them to this. I test some trying but they have syntax error:

({
  name: this.name,
  family: this.family
} = this.props);

How I can write it?

Upvotes: 1

Views: 1094

Answers (2)

Aristos Manolarakis
Aristos Manolarakis

Reputation: 1

EDIT:

1.You could use the constructor and pass the props to state. If you use arrow functions you don't have to do the binding for every function.(Although creating functions and binding compiles faster than arrow functions).

2.You could use the props inside the state and do something like this:

state={prop1: this.props.prop1,prop2: this.props.prop2,...}

And then use the state instead

3.Another solution is to use hooks which is a new feature that enables your to use state in functional components and also use props by passing them as argument in your function declaration. So your component would become from this:

class Example extends React.Component {
  state = {
   .....
  }
  .
  .
  .
  render() {
    const {prop1, prop2, ...}=this.props
    return {......};
  }
}

to this:

 function Example(props) {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);
  const {prop1, prop2, ...} = props;
  .
  .
  .
  return (
    ....
  );
}

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

You have to list all separately: (if you wanted to use in class)

name = this.props.name
family = this.props.family

But this seems unnecessary to me, you probably wanted to use in the state:

state = {
  name: this.props.name
  family: this.props.family
}

But if you need to use somewhere else, you can do:

render() {
  const { name, family } = this.props

Upvotes: 2

Related Questions