Skip to main content

到底React Hooks有何特別?

· 5 min read
戈頓
Developer & Co-founder of Tecky Academy

新近推出的React 16.7包括一個很有趣的功能,名字叫做React Hooks。看到這個名字,很多人會下意識認為是在講 componentDidMount, componentDidUpdate等方法。但其實這些方法正名是 React Lifecycle Method,推出React Hooks是為了方便開發者多用functional component,但仍然能夠使用stateprops等重要功能。

React簡介

如果你只對平常的Web Programming有認識,而未曾使用過React 的話,首先需要理解React的特別之處: 與Dom Manipulation不同,以React開發前端軟件要以component作為基本單位去思考。以下是一個 React Component的例子:

function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}

對未曾接觸過React的朋友,以上一段代碼最令人奇怪的就是一段 <h1>Hello, </h1>。

這個格式稱之為JSX,就是容許開發者將HTML 直接嵌入Javascript之中,簡化代碼的複雜程度。以上一段,就是將從 function外傳遞的值成為參數,生成對應的HTML。

const elem = <Welcome name="Sara" />
ReactDOM.render(
element,
document.getElementById('root')
);

以上這個例子,name的值就是Saraelem亦會是<h1> Hello, Sara</h1>的HTML。 就是運用了React裏面props的概念,propsproperties的簡稱,代表由外層component傳遞進來的值。

用class來建立component

要運用另外一個重要概念 state,在React Hooks出現之前,我們需要使用class component in reacts.以下是同一個component,以 class的型式重寫。

class Welcome extends React.Component{
render(){
return (
<h1>Hello, {this.props.name}</h1>
)
}
}

使用class的一大好處,就是因為this的存在,我們可以使用state來儲存不同的值,再根據不同情況改變state。 例如我們想為這個Welcome加一個counter,每一次按h1就會加上1 。Welcome 就會變成這個樣子。

class Welcome extends React.Component{
constructor(props){
super(props);
this.state = {
counter: 0
}
this.incrementCounter = this.incrementCounter.bind(this);
}
incrementCounter(){
this.setState(state=>({
counter : state.counter+1
}));
}
render(){
return (
<h1 onClick={this.incrementCounter}>
Hello, {this.props.name}
{this.state.counter} times
</h1>
)
}
}

加上React基本的設置,我們可以得到以下這個簡單的網站:

React Basic

React Hooks

本來,React的component用法就只有這兩大類,但是相信大家感受到使用functional component 簡單得多, 無需額外的一個class,只要普通一個function就已經解決了。

問題是Javascript的function不支援this, 所以也無法儲存任何state

因此,React的開發者加入了兩個非常有用的built-in functions,一個叫useState,一個叫useEffect

  • useState 幫助開發者讀取及寫入state,簡化的正是以上setState的一段代碼。
  • useEffect 幫助開發者簡化例如componentDidUpdate等的logic。

以下是一個使用了useState重寫的例子。

function Welcome(props) {
const [counter,setCounter] = useState(0);
return <h1 onClick={()=>setCounter(counter=>counter+1)}>
Hello, {props.name}
{counter} times
</h1>;
}

[counter,setCounter]前面的是counterstate,後面的是更新counterfunction。 因為我們的counter 本身是基於之前的counter去更新,所以可以直接傳遞一個functioncounter=>counter+1 去更新counter的數值。

至於useState(0)0就是counter的初始數值。

總結

加入React Hooks,簡化了開發stateful react component的難度,useEffect亦可有效分享stateful logic ,不過今次篇幅有限,暫時先介紹useState吧。