之前我們已經(jīng)掌握了useState的使用,在 class 中常遂,我們通過在構(gòu)造函數(shù)中設(shè)置 this.state
為 { count: 0 }
來初始化 count
state 為 0
:
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
在函數(shù)組件中惭婿,我們沒有 this
驾诈,所以我們不能分配或讀取 this.state
凤瘦。我們直接在組件中調(diào)用 useState
Hook:
import React, { useState } from 'react';
function Example() {
// 聲明一個叫 “count” 的 state 變量
const [count, setCount] = useState(0);
既然我們知道了 useState
的作用冤竹,那么掌握 useEffect
就更容易拂封,函數(shù)組件中沒有生命周期茬射,那么可以使用 useEffect
來替代。如果你熟悉 React class 的生命周期函數(shù)烘苹,你可以把 useEffect
Hook 看做 componentDidMount
躲株,componentDidUpdate
和 componentWillUnmount
這三個函數(shù)的組合。
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
使用 Hook 的示例
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
默認(rèn)情況下镣衡,它在第一次渲染之后和每次更新之后都會執(zhí)行霜定。你可能會更容易接受 effect 發(fā)生在“渲染之后”這種概念,不用再去考慮“掛載”還是“更新”廊鸥。React 保證了每次運行 effect 的同時望浩,DOM 都已經(jīng)更新完畢。
數(shù)據(jù)獲取惰说,設(shè)置訂閱以及手動更改 React 組件中的 DOM 都屬于副作用磨德。有些副作用可能需要清除,所以需要返回一個函數(shù)吆视,比如掛載時設(shè)置定時器典挑,卸載時取消定時器。
class Example extends Component {
constructor (props) {
super(props);
this.state = {
count: 0
}
}
componentDidMount() {
this.id = setInterval(() => {
this.setState({count: this.state.count + 1})
}, 1000);
}
componentWillUnmount() {
clearInterval(this.id)
}
render() {
return <h1>{this.state.count}</h1>;
}
}
使用 Hook 的示例
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(c => c + 1);
}, 1000);
return () => clearInterval(id);
}, []);
return <h1>{count}</h1>
}
你可以通知 React 跳過對 effect 的調(diào)用啦吧,只要傳遞數(shù)組作為 useEffect
的第二個可選參數(shù)即可您觉,如果想執(zhí)行只運行一次的 effect(僅在組件掛載和卸載時執(zhí)行),可以傳遞一個空數(shù)組([]
)作為第二個參數(shù)授滓。這就告訴 React 你的 effect 不依賴于 props 或 state 中的任何值琳水,所以它永遠(yuǎn)都不需要重復(fù)執(zhí)行。
通過跳過 Effect 進(jìn)行性能優(yōu)化般堆,在某些情況下在孝,每次渲染后都執(zhí)行清理或者執(zhí)行 effect 可能會導(dǎo)致性能問題。在 class 組件中淮摔,我們可以通過在 componentDidUpdate
中添加對 prevProps
或 prevState
的比較邏輯解決:
componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
document.title = `You clicked ${this.state.count} times`;
}
}
這是很常見的需求私沮,所以它被內(nèi)置到了 useEffect
的 Hook API 中。如果某些特定值在兩次重渲染之間沒有發(fā)生變化和橙,你可以通知 React 跳過對 effect 的調(diào)用仔燕,只要傳遞數(shù)組作為 useEffect
的第二個可選參數(shù)即可:
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // 僅在 count 更改時更新
你已經(jīng)學(xué)習(xí)了 State Hook 和 Effect Hook,將它們結(jié)合起來你可以做很多事情了胃碾。它們涵蓋了大多數(shù)使用 class 的用例。