iT邦幫忙

2021 iThome 鐵人賽

DAY 8
0
自我挑戰組

React自我學習心得30天~系列 第 8

Day8 React State(編輯中)

State概要

React Component 只能透過資料狀態的改變來更新UI,資料來源來自於以下兩種方式:

  • 透過外部傳進來Component的 Props
  • Component內部自己的 State
    當Props或State的資料有更新時,React就會刷新一次UI。

class Component中的constructor()用 this.state初始化State物件;若要存取使用的話也是透過this.stat。更新State的資料時,使用 React提供的方法 this.setState()更新 State。

下面用一個clock Component作為state範例,透過Sta:

class Clock extends React.Component {

  // 當Component被 ReactDOM.render() 渲染到畫面時,React 會先執行constructor裡的邏輯判斷
  constructor(props) {
    super(props);

    // 初始化state 資料,可以放物件、字串、或陣列
    this.state = {date: new Date()};
  }

  // React call render() 拿到要顯示到 DOM 的元素內容
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

修改state

用下列的方式更新constructor()之外的State。

this.setState(更新的內容);

setState相關語法介紹

React為了效能的考量,會將好幾次的this.setState()統整後再做一次更新,這表示執行完this.setState()後,下一行this.state不一定能取得最新的State。
以下的語法可以取得當前最新的State和prop:

this.setState( (prevState, props) => stateChange )

prevState和props分別為當前最新的State和props。

State和Props為非同步更新的緣故,React有一個callback function可以在更新完State時進行邏輯判斷。

setState(stateChange, callback function)

上一篇
Day7 認識Components與 Props
下一篇
Day9 React生命週期
系列文
React自我學習心得30天~30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言