iT邦幫忙

2021 iThome 鐵人賽

DAY 24
1
自我挑戰組

Re: 從 Next.js 開始的 React 生活系列 第 24

[Day24] 在 Codecademy 學 React ~ 終於來到 Hook 的世界 ‧ useState 篇 (1)

前言

看到今天標題 useState
你可能會說我前面不是講過了嗎XD
其實之前那樣算是直接跳過第一、二階段,
直接來到第三階段,
還記得前幾天的文章我一直在跟 this.props, this.state,還有 this.setState 奮鬥(?),
這算是第一階段的看山是山,
今天的文章一開始會講一點不用 this 的用法,這是第二階段的看山不是山,
再來就會進入本日重頭戲第三階段的看山又是山 - useState 囉~
而且在 Codecademy 上進入 useState 學習之前,
我也是天真的以為我都會了,
沒想到真的學了才發現有很多東西我還不會,
因此當作複習跟吸收新知,
大家就再跟著我的腳步來到 useState 的世界吧!

本日正文

不需要用 this 的 props 取用方法

還記得我們之前如果要宣告一個 componenet 都要落落長寫這樣的程式:

class XXX extends React.Component {
	render() {
		return (
		)
	}
}

而且如果要在 class 裡面取用屬性的值,
必須要寫 this.props.屬性
像這樣:

<div>
	<h1>這是一個{this.props.name}</h1>
	<h1>顏色:{this.props.color}</h1>
	<h1>價格:{this.props.price}元</h1>
</div>

有個好消息,Codecademy 教了一個寫法不用再寫這麼落落長的語法,
這邊把前幾天寫的範例再貼一次:

Fruit.js

export class Fruit extends React.Component {
  render() {
    return (
      <div>
        <h1>這是一個{this.props.name}</h1>
        <h1>顏色:{this.props.color}</h1>
        <h1>價格:{this.props.price}元</h1>
      </div>
    );
  }
}

現在我們只要寫成這樣就好囉!

export const Fruit = (props) => {
  return (
    <div>
      <h1>這是一個{props.name}</h1>
      <h1>顏色:{props.color}</h1>
      <h1>價格:{props.price}元</h1>
    </div>
  );
};

而且在 App.js 跟之前一樣使用 <Fruit>
<Fruit name="蓮霧" color="淺紅色" price="200" />
發現就可以達成一樣效果,這樣的寫法是不是簡單很多呢?
https://ithelp.ithome.com.tw/upload/images/20210926/20129873uCTpZV4FPX.png

這就是第二階段的寫法,
接下來要進入第三階段囉XD

Hook - useState

在 React 16.8+ 版本以後提供了 Hook 的方式,
讓宣告及使用 componenet 變得更加簡便,
常見的 Hook 有:useState(), useEffect(), useContext(), useReducer(), and useRef()
對完整的 Hook 有興趣的人可以參考這篇→ Hooks API Reference

在正式進入 useState 之前,
讓我們回憶一下,
之前在改變天氣的例子中,
還記得我們是怎麼寫的嗎?

  1. 首先宣告一個 class Weather
export class Weather extends React.Component
  1. 裡面要使用 constructor(props),裡面還要宣告一個 weather 的 state
constructor(props) {
    super(props);
    this.state = { weather: "sunny" };
    
  }
  1. 再來還要宣告改變天氣的 function changeWeather,裡面要用到 this.setState
changeWeather() {
    const newWeather = this.state.weather === "sunny" ? "rainy" : "sunny";
    this.setState({ weather: newWeather });
  }
  1. 然後別忘了在 constructor 裡面要把 changeWeather 跟 this bind 起來
this.changeWeather = this.changeWeather.bind(this);
  1. 在按鈕的 onClick 事件宣告呼叫 this.changeWeather
  render() {
    return (
      <div>
        <h1>今天天氣:{this.state.weather}!</h1>
        <button onClick={this.changeWeather}>改變天氣</button>
      </div>
    );
  }
}

經過這 5 個步驟才能達到我們按按鈕切換天氣的功能,
可是你知道用 useState 改寫後變得多輕鬆寫意嗎?

讓我們來改寫看看吧!

  1. 首先要在第一行 import { useState }
import React, { useState } from "react";
  1. 再來宣告 Weather 的 class,一樣用上面提到的 const 語法即可
export const Weather = () => {  
};
  1. 再來在 Weather 的 class 裡面宣告 weather 狀態,並使用 useState
const [weather, setWeather] = useState('sunny');

這句的意思是 有一個 weather 狀態,初始值用 useState 設為 sunny,
之後改變 weather 的 function 就是 setWeather。

Codecademy 對於 useState 的詳細說明如下,
useState 包含兩個值:current state(現在狀態的值)、以及 state setter (改變狀態的 function)

useState() is a JavaScript function defined in the React library. When we call this function, it returns an array with two values:
current state - the current value of this state
state setter - a function that we can use to update the value of this state

  1. 然後只要直接在按鈕的 onClick 事件寫 setWeather,
    不需要像之前還要再另外宣告 function 跟 bind this,
    像這樣:
return (
    <div>
      <h1>今天天氣:{weather}!</h1>
      <button
        onClick={() =>
          weather === 'sunny' ? setWeather('rainy') : setWeather('sunny')
        }
      >
        改變天氣
      </button>
    </div>
  );

這邊說明一下 weather === 'sunny' ? setWeather('rainy') : setWeather('sunny')
這句意思是,判斷 weather 值是否為 'sunny',是的話就執行 setWeather 將 weather 值改為 'rainy',
不是的話就執行 setWeather 將 weather 值改為 'sunny'。

是不是簡單很多!
也不用在那邊寫落落長的 constructor, props, function,
還會三不五時忘記 bind orz
用更簡單的寫法卻能達成一樣的效果,
React 真是造福人群QQ

今日範例雖然是改寫之前的,
不過還是附上來→ Day24 - useState (Codecademy)

然後再附上兩種寫法的截圖,
大家應該一看就覺得哪種寫法比較簡單又方便又好懂了吧XD
https://ithelp.ithome.com.tw/upload/images/20210926/20129873WuPCptlGSs.png

後記

其實這邊只是初步介紹 useState,
算是再讓大家感受一下從 this.state, this.setState 到 useState 的差別,
這樣大家可能也比較能了解為什麼對於一開始就學 useState 寫法的我來說,
要再跳回去寫那些落落長的寫法會有點適應不良了orz

Codecademy 對於 useState 的教學還有更進階的用法,
就讓我留到明天文章吧XD


上一篇
[Day23] 在 Codecademy 學 React ~ Component Lifecycle 生命週期我不懂你QQ
下一篇
[Day25] 在 Codecademy 學 React ~ 終於來到 Hook 的世界 ‧ useState 篇 (2)
系列文
Re: 從 Next.js 開始的 React 生活31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言