Hooks学习

useState(hooks最基础)

  1. 数组解构 useState
	const [count, setCount] = useState(0);  // ES6的数组解构的方法
  // 即  全等于 === 
  let _userState(0);
  let count = useState(0);
  let setCount = _userState[1];
  1. useState 不能存在于 条件 判断语句当中
React Hook "useState" is called conditionally.
生命周期函数(类组件中使用)
  1. componentDidMount 与 componentDidUpdate
  // 刚开始渲染的时候--生命周期函数
  componentDidMount() {
    console.log(`componentDidMount=> You Clicked ${this.state.count},执行了--渲染--时候的生命周期函数`);
  }
  // 更新的时候--生命周期函数
  componentDidUpdate() {
    console.log(`componentDidUpdate=> You Clicked ${this.state.count},执行了--更新--时候的生命周期函数`);
  }

例图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aEJtNl7F-1622378298863)(Hooks相关的学习.assets/image-20210427195702903.png)]

useEffect(hooks最基础)

  1. 相当于 : componentDidMount + componentDidUpdate 两个生命周期函数。
  useEffect(() => {   
    // 相当于两个生命周期函数 ===  componentDidMount + componentDidUpdate
  })
  • 当数组存在并有值时,如果数组中的任何值发生更改,则每次渲染后都会触发回调。
  • 当它不存在时,每次渲染后都会触发回调。
  • 当它是一个空列表时,回调只会被触发一次,类似于 componentDidMount。
  1. useEffect 是异步函数,不会影响视图更新
  2. useEffect 函在件清除 effect 创建的资源时,需要返回一个清除函数:
  useEffect(() => {
    const subscription = props.soure.subscribe();
    return () => {
      // 清除函数
      subscription.unsubscribe();
    }
  })

为了防止内存泄漏,清除函数会在组件卸载前执行。另外,如果组件多次渲染,则执行下一个 effect 之前,上一个 effect 就已经被清除。

这就意味着每次更新都会创建新的订阅。

生命周期函数 – 挂载

1、componentWillMount 将要装载,在render之前调用;

componentDidMount,(装载完成),在render之后调用

2、componentWillMount 每一个组件render之前立即调用;

componentDidMount render之后并不会立即调用,而是所有的子组件都render完之后才可以调用

3、componentWillMount 可以在服务端被调用,也可以在浏览器端被调用;

componentDidMount 只能在浏览器端被调用,在服务器端使用react的时候不会被调用
img

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值