React-Hooks

Hooks

React16.7alpha新版本中新增useState useEffect等API;

函数式编程将业务逻辑从展示组件中剥离出来,结构更加清晰;
通过hooks将UI组件和数据更加清晰得分离开;
UI组件使用纯函数进行表达;
useState useEffect来代替react常规组件中的生命周期钩子函数;

React常规组件实现业务逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import React,{Component} from 'react';
class Container extends Component{
constructor(props){
super(props)
this.state={
count:0
}
this.handleChangeCount = this.handleChangeCount.bind(this)
}
handleChangeCount(){
this.setState({
count:this.state.count++
})
}
render(){
return(
<div>
<p>{this.state.count}</p>
<button onClick = {this.handleChangeCount}>点击增加</button>
</div>
)
}

}

React-Hooks实现数字累加逻辑组件

  • 对useState使用解构,类似constructor构造器初始化数据;
  • useEffect当数据改变时的钩子函数;
  • useEffect的第二个参数是一个数组,钩子函数会根据数组的数据变化而执行;
  • setCount相当于setState函数,对数据进行更新
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    import react,{Component,useState,useEffect} from 'react';
    function CountChange(props){
    // 类似constructor构造器初始化数据
    const [count,setCount] = useState(0)
    // side effect函数 当数据改变时的钩子函数
    // componentDidMount、componentDidUpdate的结合体
    useEffect(()=>{
    documents.title = `you clicked ${count} times`
    },[count])

    return(
    <div>
    <p>you clicked {count} times</p>
    // setCount相当于setState函数,对数据进行更新
    <button click ={()=>{setCount(count+1)}}>点击增加</button>
    </div>
    )
    }

通过Hooks自定义钩子,抽离可复用的逻辑代码

  • 应用场景 当两个组件需要公用一个逻辑对自己组件内部的状态进行判断
  • 抽离公共逻辑,进行自定义钩子的封装
  • 使用useEffect函数需return一个函数,类似removeEventListener移除事件;
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    import react,{ useState, useEffect} from 'react';
    // 抽离custom logic
    function useFriendStatus(friendID){
    const [isOline, setIsOline] = useState(null)
    function handleStatusChange(status){
    setIsOline(status.isOline)
    }

    useEffect(()=>{
    chatAPI.subscribetoFriendStatus(friendID,handleStatusChange)
    return chatAPI.unsubscribefromFriendStatus(friendID,handleStatusChange)
    })

    return {
    isOline
    }
    }

    // 在其他组件使用这个公用hooks
-------------本文结束感谢您的阅读-------------