下面的 React js 代码 formatCount 函数是如何工作的?
How the below React js code formatCount function works?
我正在学习 React.js 并面临以下令人困惑的代码:
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;
有几件事让我感到困惑:
1.state
是一个对象而不是一个数字,但是在这一行const {counts} = this.state;
为什么要将一个对象分配给一个数字?
2.Why using {}
on counts,但下一行,没有 {}
around counts,return counts === 0 ? 'Zero' : counts
?
const {counts} = this.state;
被称为 object destructuring 并且本质上是一种更短的写法:
const counts = this.state.counts;
return counts === 0 ? 'Zero' : counts
是 ternary operator 的一种用法,例如被用来代替 if/else 这样的语句:
if (counts === 0) {
return 'Zero';
} else {
return counts;
}
我正在学习 React.js 并面临以下令人困惑的代码:
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;
有几件事让我感到困惑:
1.state
是一个对象而不是一个数字,但是在这一行const {counts} = this.state;
为什么要将一个对象分配给一个数字?
2.Why using {}
on counts,但下一行,没有 {}
around counts,return counts === 0 ? 'Zero' : counts
?
const {counts} = this.state;
被称为 object destructuring 并且本质上是一种更短的写法:
const counts = this.state.counts;
return counts === 0 ? 'Zero' : counts
是 ternary operator 的一种用法,例如被用来代替 if/else 这样的语句:
if (counts === 0) {
return 'Zero';
} else {
return counts;
}