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>
);
}
}
當(dāng)我們想要在每次render之后執(zhí)行時在class組件中需要在commponentDidMount和componentDidUpdate中都調(diào)用事件。
而在hook中就只需要在useEffect中調(diào)用就可以:
import { 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>
);
}
useEffectHooks視作componentDidMount、componentDidUpdate和componentWillUnmount的結(jié)合。useEffect會在每次render之后調(diào)用。
當(dāng)不需要清理時可以直接:
useEffect(() => {
document.title = `You clicked ${count} times`;
});
當(dāng)需要清理時(如定時器)需要返回一個函數(shù):
useEffect(() => {
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
注意:
useEffect的第二個參數(shù)必須傳空數(shù)組,這樣它就等價于只在componentDidMount的時候執(zhí)行。如果不傳第二個參數(shù)的話,它就等價于componentDidMount和componentDidUpdate
import React, { useEffect } from 'react'
?
export function BusinessComponent() {
const initData = async () => {
// 發(fā)起請求并執(zhí)行初始化操作
}
// 執(zhí)行初始化操作,需要注意的是,如果你只是想在渲染的時候初始化一次數(shù)據(jù),那么第二個參數(shù)必須傳空數(shù)組。
useEffect(() => {
initData();
}, []);
?
return (<div></div>);
}
但是有時候我們想在用戶輸入新的id時再進(jìn)行查詢和處理操作我們可以在useEffect中傳入第二個參數(shù),那么就只有在第二個參數(shù)發(fā)生變化(首次渲染)的時候才會觸法effects.
import React, { useEffect } from 'react'
?
export function QRCode(url, userId) {
// 根據(jù)userId查詢掃描狀態(tài)
const pollingQueryingStatus = async () => {
}
?
const stopPollingQueryStatus = async() => {
}
// 我們只是將useEffect的第二個參數(shù)加了個userId
useEffect(() => {
pollingQueryingStatus();
?
return stopPollingQueryStatus;
}, [userId]);
?
// 根據(jù)url生成二維碼
return (<div></div>)
}