I'm learning React.js and facing the below confusing code:
import React, { Component } from 'react';
class Counter extends Component {
state = {
counts:1
};
render() {
return (
<React.Fragment>
<span>{this.formatCount()}</span>
<button>Increment</button>
</React.Fragment>
);
}
formatCount(){
const {counts} = this.state;
return counts === 0 ? 'Zero' : counts
}
}
export default Counter;
A few things confuse me:
1.state
is an object rather than a number, but in this line const {counts} = this.state;
why assigning an object to a number?
2.Why using {}
on counts, but the next line, no {}
around counts, return counts === 0 ? 'Zero' : counts
?
const {counts} = this.state;
is called object destructuring and is essentially a shorter way of writing this:
const counts = this.state.counts;
return counts === 0 ? 'Zero' : counts
is a use of the ternary operator and can e.g. be used instead of if/else statements like this one:
if (counts === 0) {
return 'Zero';
} else {
return counts;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments