iT邦幫忙

2022 iThome 鐵人賽

DAY 3
2

一、state 值到底是什麼?

記得我剛寫 React 時,我都還不太熟變數到底怎麼運用,新手們千萬不要害怕阿!寫久了就會了!如果一直沒學會的話可以看看我這篇文章。

state 值就像是你為某一個參數定義的一個初始值,你有可能在某些動作後,改變那個預設值,在改變 state值後,將會透過自動重新呼叫 render() 更新你的頁面。

然而基本上我自己將 state 認知為一個頁面的暫存值,這裡的「頁面」指的是這一個 component,也就是它可以作用的範圍。也就是說如果你的頁面架構是下圖這樣的組成方式,那你是沒有辦法在 header 拿到 component 的任何 state。

https://ithelp.ithome.com.tw/upload/images/20220918/20140920ASNGaovfps.png
頁面組成範例圖

二、以官網首頁範例來說

下列程式碼是一個自動計算秒數並呈現的範例。在 constructor 裡的 this.state 就是在這個 component 裡可呼叫的 state 值,那它通常會是一個 object,方便後續呼叫使用。

class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { seconds: 0 };
  }
/*這裡有省略的程式碼*/
  render() {
    return (
      <div>
        Seconds: {this.state.seconds}
      </div>
    );
  }
}

root.render(<Timer />);

17.0 版本的 React 則會寫成下面這樣

class Timer extends React.Component {
  const [seconds, setSeconds] = useState(0);
/*這裡有省略的程式碼*/
  render() {
    return (
      <div>
        Seconds: {this.state.seconds}
      </div>
    );
  }
}

root.render(<Timer />);

三、state 的使用方式

掌握下面三原則,基本上你就可以好好運用這個方便的小工具做出更多網頁上的變化啦~

1. 宣告

// 16.9 版
constructor(props) {
    this.state = { 
        seconds: 0 
    };
}

// 17.0 版
const [seconds, setSeconds] = useState(0);

2. 呼叫

// 16.9 版
    {this.state.seconds}
// 17.0 版
    seconds

3. 使用

// 16.9 版
   this.setState({
       seconds: this.state.seconds + 1
   })
   
// 17.0 版
    setSeconds(seconds + 1)

參考資源:React 官網


上一篇
Day02:直接來一個 component 了啦
下一篇
Day04:前後端都必學的工具大禮包—lodash.js
系列文
你終究都要...學會 React ,何不一開始就看我一眼? 9
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

0
隱士者
iT邦新手 4 級 ‧ 2022-09-19 09:07:21

感覺17.0版的寫法比較好看,只需要看左邊就知道seconds變數可以使用

Annie iT邦新手 2 級 ‧ 2022-09-19 10:07:51 檢舉

我自己也比較喜歡17.0的寫法(握手),但團隊同事目前是喜歡16.9的居多,因為16.9的可以一次改變多個state值。

0
kk00915
iT邦新手 4 級 ‧ 2022-09-22 15:21:28

17.0的簡潔很多

我要留言

立即登入留言