新近推出的React 16.7包括一個很有趣的功能,名字叫做React Hooks。看到這個名字,很多人會下意識認為是在講componentDidMount, componentDidUpdate等方法。但其實這些方法的正名是 React Lifecycle Method, 推出React Hooks是為了方便開發者多用functional component,但仍然能夠使用state及 props等重要功能。
React 簡介
如果你只對平常的 Web Programming 有認識,而未曾使用過React 的話,首先需要理解React的特別之處: 與 Dom Manipulation 不同,以 React 開發前端軟件要以 component作為基本單位去思考。以下是一個 React Component 的例子:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
對未曾接觸過 React 的朋友,以上一段代碼最令人奇怪的就是一段<h1>Hello, {props.name}</h1>。這個格式稱之為 JSX,就是容許開發者將 HTML 直接嵌入 Javascript 之中,簡化代碼的複雜程度。以上一段,就是將從 function 外傳遞的值成為參數,生成對應的HTML。
const elem = <Welcome name="Sara" />
ReactDOM.render(
elem,
document.getElementById('root')
)
以上這個例子,name 的值就是
Sara
,elem 亦會是 <h1>Hello, Sara</h1> 的HTML。就是運用了 React 裏面
props
的概念,props 是 properties 的簡稱,代表由外層component傳遞進來的值。用 class 來建立 component
若然需要運用 React 另外一個重要概念
state
,在 React Hooks 出現之前,我們只能使用 React 的 class component。以下是同一個 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 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} timers
</h1>;
}
[counter,setCounter]
前面的是 counter 的 state,後面的是更新 counter 的 function。因為我們的 counter 本身是基於之前的 counter 去更新,所以可以直接傳遞一個 function 像
counter => counter + 1
去更新 counter 的數值。至於 useState(0) 的 0 就是 counter 的初始數值。
總結
加入 React Hooks,簡化了開發 stateful react component 的難度,
useEffect
亦可有效分享 stateful logic ,不過今次篇幅有限,暫時先介紹 useState
吧。__________________________________________________________
文章出處簡介:
Tecky Academy
三位熱心教學的開發者所創辦的成年人 programming 學校,唔係教 STEM,唔係求其教下網站,全部打真章!
高抬各巴絲貴手 like/follow 我地嘅 Facebook: http://bit.ly/2BPcSmB
有咩問題可以 tg 小弟: https://t.me/itdogltd