简单介绍一下hook中useEffect在函数组件使用可以代替类组件中的哪些生命周期和写法
1、useEffect代替componentDidMount的写法
类组件的写法
class Example extends React.Component {
componentDidMount() {
console.log('Did mount!');
}
render() {
return <div></div>;
}
}
函数组件的写法
function Example() {
// 当我们指定第二个参数为空数组就可以代替我们类组件中的componentDidMount
useEffect(() => {
console.log('Did mount!');
}, []);
return <div></div>;
}
2、useEffect代替componentDidUpdate的写法
类组件的写法
class Example extends React.Component {
componentDidUpdate() {
console.log('Did update!');
}
render() {
return <div></div>;
}
}
函数组件的写法
function Example() {
// 当我们第二个参数监听一个状态的时候代替componentDidUpdate
useEffect(() => {
console.log('Did update!');
},[a]);
return <div></div>;
}
3、useEffect代替componentWillUnmount的写法
类组件的写法
class Example extends React.Component {
componentWillUnmount() {
console.log('Will unmount!');
}
render() {
return <div></div>;
}
}
函数组件的写法
function Example() {
// 当我们不指定第二个参数的同时并在第一个参数中返回一个函数就可以代替我们类组件中的componentWillUnmount
useEffect(() => {
return () => {
console.log('will unmount');
}
});
return <div></div>;
}
不得不说自从出了hooks,react越来越好写了