使用 useEffect 代替旧生命周期函数以及 Callback
文章目录

React V16.8+

For componentDidMount

1
2
3
useEffect(() => {
// Your code here
}, []); // 这个地方没有依赖,所以只执行一次

For componentDidUpdate

1
2
3
useEffect(() => {
// Your code here
}, [yourDependency]);

For componentWillUnmount

1
2
3
4
5
6
useEffect(() => {
// componentWillUnmount
return () => {
// Your code here
}
}, [yourDependency]);

So in this situation, you need to pass your dependency into this array. Let’s assume you have a state like this

1
const [count, setCount] = useState(0);

And whenever count increases you want to re-render your function component. Then your useEffect should look like this

1
2
3
useEffect(() => {
// <div>{count}</div>
}, [count]);

代替 Callback

第二个参数是依然列表, 完全可以在 loading 获得数据或者完成的时候调用 callback

1
2
3
4
5
useEffect(() => {
if (!loading) {
// callback here
}
}, [loading])

异步处理的模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
export default function Example() { 
const [data, dataSet] = useState(false)



async function fetchMyAPI() {
let response = await fetch('api/data')
response = await res.json()
dataSet(response)
}

useEffect(() => {
fetchMyAPI();
}, []);



return <div>{data}</div>
}