iT邦幫忙

2021 iThome 鐵人賽

0
自我挑戰組

Be friend with JavaScript系列 第 35

React Hooks - useState

前一篇有提到在 function component 沒有 this,不能使用 this.state 及 this.setState(),這時候我們就需要使用 Hook 的 useState 解決這個問題。
useState 會回傳一對值 - 目前的 state 和 一個可以更新 state 的 function。
用法:
const [state, setState] = useState(initialState)
state 存放 state 的值,setState 設定 state 的值(用來更新 state),而 initialState 為第一次 render 時回傳的 state 初始值。
setState(newState)
setState function 用來更新 state。

const [state, setState] = useState(initialState) 為解構賦值後的寫法,下面會舉例非解構賦值的寫法。

將前一篇 class component state 改成 function component 的 useState:

import React, { useState } from "react";
const Hookstate = () => {
  const [count, setCount] = useState(0);
  return (
    <div>
      <h3>Hook - useState</h3>
      <p>You clicked {count} times</p>
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Click
      </button>
    </div>
  );
};
export default Hookstate;

前面有提到 useState 的語法是解構賦值,以上面程式碼中的 count 為例,const [count, setCount] = useState(0),在解構賦值的寫法其實就是:

const state = useState(0);
const count = state[0];
const setCount = state[1];
  • 如果新的 state 是用之前的 state 計算出,就要在 setState 裡寫一個 function,function 將接收先前的 state,並回傳一個已更新的值。

例如:

import React, { useState } from "react";
const Hookstate = () => {
  const [count, setCount] = useState(0);
  console.log("count : "+ count);
  return (
    <div>
      <h3>Hook - useState</h3>
      <p>You clicked {count} times</p>
      <button
        onClick={() => {
          setCount(count => count + 1);
          setCount(count => count + 1);
          setCount(count => count + 1);
        }}
      >
        Click
      </button>
      <br />
    </div>
  );
};
export default Hookstate;

在 setCount() 裡面放一個 function,它會自動去計算之前的值,執行上面的程式碼後,按下 click 時 count 會變成 3,再按一下會變成 6,每次都加 3。


如果是在 setCount() 裡面直接計算值,則每次的結果會被後面的結果覆蓋掉,例如:

import React, { useState } from "react";
const Hookstate = () => {
  const [count, setCount] = useState(0);
  console.log("count : "+ count);
  return (
    <div>
      <h3>Hook - useState</h3>
      <p>You clicked {count} times</p>
      <button
        onClick={() => {
          setCount(count + 1);
          setCount(count + 1);
          setCount(count + 1);
        }}
      >
        Click
      </button>
      <br />
    </div>
  );
};
export default Hookstate;

執行上面的程式碼後,按下 click 時 count 會變成 1,再按一下變成 2,即使在 onClick 的 function 裡面寫了好幾次 setCount(count + 1),最後結果都只會加 1。

參考資料:
https://zh-hant.reactjs.org/docs/hooks-reference.html#usestate
https://medium.com/hannah-lin/react-hook-%E7%AD%86%E8%A8%98-%E5%BE%9E%E6%9C%80%E5%9F%BA%E6%9C%AC%E7%9A%84-hook-%E9%96%8B%E5%A7%8B-usestate-useeffect-fee6582d8725


上一篇
React - Props & State
下一篇
React Hooks - useEffect
系列文
Be friend with JavaScript39
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言