react-hooks小试牛刀

react-hooks的基本使用

1 class组件

  1. 引入Component
  2. 组件基础component
  3. 导出组件类

1.1 state

import React, { Component } from 'react';
class CountDemo extends Component {
  constructor(props) {
    super(props);
    this.state = { count:0 }
  }
  render() { 
    return (
      <>
        <p>you click { this.state.count} times!</p>
        <button onClick={this.btnClick.bind(this)}>Click me!</button>
      </>
    );
  }
  btnClick(){
    this.setState({
      count:this.state.count+1
    })
  }
}
 
export default CountDemo;

出现的问题:

  • 变量的引用麻烦,需要添加this.state
  • 方法的引用需要注意绑定作用域

1.2 生命周期

import React, { Component } from 'react';

class CountDemo extends Component {
  constructor(props) {
    super(props);
    this.state = { count:0 }
  }

  componentDidMount(){
    console.log(`componentDidMount->${this.state.count}`)
  }
  componentDidUpdate(){
    console.log(`componentDidUpdate->${this.state.count}`)
  }
  render() { 
    return ( 
      <>
        <p>you click { this.state.count} times!</p>
        <button onClick={this.btnClick.bind(this)}>Click me!</button>
      </>
    );
  }
  btnClick(){
    this.setState({
      count:this.state.count+1
    })
  }
}
 
export default CountDemo;
  • 出现问题

两个生命周期里面编写重复代码。

生命周期:

  • 挂载卸载过程
  1. constructor(props, context)
  2. componentWillMount()
  3. componentDidMount()
  4. componentWillUnmount()
  • 更新过程
  1. componentWillReceiveProps(nextProps)
  2. shouldComponentUpdate(nextProps,nextState)
  3. componentWillUpdate(nextProps,nextState)
  4. componentDidUpadate(prevProps,prevState)
  5. render()

2 function组件[react-hooks]

  1. 引入定义状态的方法(useState)
  2. 引入其他hook处理
  3. 导出组件函数

2.1 state=>useState

定义状态变量使用 useState:(进行值初始化,并拥有一个重新定义值的方法)

const [count,setCount] = useState(0)

所以,以上的例子可以简写为

import React, { useState } from 'react';

function CountDemo(){
 
  const [count,setCount] = useState(0)
  return(
    <>
      <p>you click { count} times!</p>
      <button onClick={()=>{setCount(count+1)}}>Click me!!!</button>
    </>
  )
}

export default CountDemo

注意:useState 根据定义顺序,来确定各个状态的key,所以不能把状态放在if语句里面。

if(true){
 const [name,setName] = useState('rhlee')
}

/*
报错如下:

React Hook "useState" is called conditionally. 

React Hooks must be called in the exact same order in every component render
*/

2.2 生命周期=>useEffect

useEffect Hook 相当于:

componentDidMountcomponentDidUpdatecomponentWillUnmount 这三个函数的组合。

  • useEffect()
    • 函数体:componentDidMountcomponentDidUpdate
    • 返回值:componentWillUnmount
useEffect(() => {
    
    // 执行组件挂载完成/组件更新完成的生命周期
    console.log(`componentDidUpdate->${this.state.count}`)
    // Specify how to clean up after this effect:
    return function cleanup() {
      // 清除引用的变量,计时器等的清除。
    };
  });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值