Released 2023-03-23

Modified 2023-03-23

Tech

737Words (4min read)

[Day 30] React 的狀態管理 - 嘗試 30 日寫文充版挑戰

Title Image

Photo by React on React

前言 - Prologue

嘗試寫 30 天文充實版面 (跳過假日 ლ(́◕◞౪◟◕‵ლ) ) 挑戰更新文章的最後一天 !!!

本筆記將整理 React 中的狀態管理相關概念和技巧,包括 statesetStateuseState 等。通過一邊筆記一邊學習可以更好地掌握 React 中的狀態管理方法,提高開發效率和程式碼質量。

正文 - Main text

當在 React 應用程序中需要管理狀態時,可以使用 statesetStateuseState 來實現。

1. state 是 React 元件內部管理的一個專用對象,用於存儲元件狀態資料。當 state 資料發生變化時,React 會自動重新渲染元件。

2. setState 是用於修改元件 state 的方法,當調用 setState 時,React 會更新 state 並重新渲染元件。

3. useState 是一個 React hook,可以使開發人員在函數式元件中使用狀態。它接收一個初始值,並返回一個陣列,第一個元素是當前的狀態值,第二個元素是更新狀態的函數。

接下來將逐一搭配範例對 statesetStateuseState 的詳細介紹。


state

用於存儲狀態數據的對象,通常在構造函數中初始化。

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }
  render() {
    return <div> { this.state.count } </div>;
  }
}
setState

用於更新元件狀態的方法。它接受一個對象作為參數,該對象描述了要更新的狀態。

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }
  handleClick = () => {
    this.setState({ count: this.state.count + 1 });
  };
  render() {
    return (
      <div>
        <div> { this.state.count } </div>
        <button onClick={this.handleClick}> Click me </button>
      </div>
    );
  }
}
useState

是一個 React hook,可以使開發人員在函數式元件中使用狀態。useState 返回一個包含狀態和狀態更新函數的陣列。

function Counter() {
  const [count, setCount] = useState(0);
  const handleClick = () => {
    setCount(count + 1);
  };
  return (
    <div>
      <div> { count } </div>
      <button onClick={handleClick}> Click me </button>
    </div>
  );
}

使用 statesetStateuseState 可以方便地管理 React 應用程序中的狀態,並且可以更快地開發應用程序。

※ 注意事項:

  • 不要直接修改 state 對象,而是使用 setState 更新狀態。
  • setState 方法是異步的,如果需要在狀態更新後執行某些操作,可以使用 useEffect hook
  • useState hook 只能在函數式元件中使用,不能在類元件中使用。
  • 當使用 useState 時,必須在函數元件的最頂層使用,不可在循環、條件語句或嵌套函數中使用。

參考資料 - Reference

[1] Using the State Hook – React

https://legacy.reactjs.org/docs/hooks-state.html

[2] Handling Events – React

https://legacy.reactjs.org/docs/handling-events.html

後記 - Epilogue

終於來到第 30 天,期間跳過了一些國定假日與特休假 (*´∀`)~♥ (欸)

不知不覺就累積到了 60 篇文章,可喜可賀,版面整個充實起來了~ 接下來就是專注學習邊更新想更新的東西啦!

[Day 30] React 的狀態管理 - 嘗試 30 日寫文充版挑戰

https:///en/blog/52

Author

Kama

Read more from Tech
lightbox-image
Toggle Button - Red Pandas Icons by svgrepo.com

Copyrights © 2023 Kama, All Rights Reserved.