hardik beladiya
hardik beladiya

Reputation: 287

How to write neat and clean code in React componentWillReceiveProps method with using nextProps Value

componentWillReceiveProps(nextProps) {
  this.setState({executor : nextProps.executor, wife : nextProps.wife});

  // Some filtering and functional Operation on nextProps value of wife and executor.
}

I want to optimise the code above.

Upvotes: 1

Views: 86

Answers (4)

UtkarshPramodGupta
UtkarshPramodGupta

Reputation: 8152

Use the new getDerivedStateFromProps.

Use the new getDerivedStateFromProps method to do the same if you are using React 16 as componentWill*** methods are being deprecated now. Also, please note that it's a static method. Read more about this new method here.

static getDerivedStateFromProps(props, state) {
    return {
      props.executor,
      props.wife
    }
}

Upvotes: 1

Idan Hen
Idan Hen

Reputation: 467

Using ES6 destruction, also added default object value to be safe.

componentWillReceiveProps({executor, wife} = {}) {
   this.setState({executor, wife});
}

Upvotes: 0

Manoz
Manoz

Reputation: 6587

If nextProps has only two objects executor and wife you can set it in one line

componentWillReceiveProps(nextProps) {
  this.setState(nextProps,()=>{
    // Your callback after it sets the state
    // Some filtering and functional Operation on nextProps value of wife and executor.
  });
}

Or go with the way as @Harsh answered by defining a constant

const {executor, wife} = nextProps;
this.setState({executor, wife});

Upvotes: 1

user7933561
user7933561

Reputation:

componentWillReceiveProps(nextProps) {
  const {executor, wife} = nextProps;
  this.setState({executor, wife});

  // Some filtering and functional Operation on nextProps value of wife and executor.
}

this way you can optimize and use the variable like wife without any changing the value.

Upvotes: 1

Related Questions