下面的React js代码formatCount函数如何工作?

问题描述 投票:2回答:1

我正在学习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.为什么在计数上使用{},但下一行,没有{}计数,return counts === 0 ? 'Zero' : counts

javascript javascript-objects ternary-operator
1个回答
1
投票

const {counts} = this.state;被称为object destructuring,本质上是一种较短的写作方式:

const counts = this.state.counts;

return counts === 0 ? 'Zero' : countsternary operator的用途,例如用来代替像这样的if / else语句:

if (counts === 0) {
  return 'Zero';
} else {
  return counts;
}
© www.soinside.com 2019 - 2024. All rights reserved.