React Hook中useEffect代替的生命周期

简单介绍一下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越来越好写了

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值