版本
React16.8 版本中添加了 hooks
- 在函数组件中使用useStatus钩子去管理state
- 在函数组件中使用useEffect钩子去使用生命周期函数
- 自定义Hook用以复用不同组件之间的状态逻辑
清理原有代码的时间消耗不亚于自己重写一套逻辑
UseState
- 动机
- 管理state
- useState钩子 (初值)
- 注:不会把新的state和旧的state进行合并
- 管理state
- 首次调用 → 初始化
- 第二次调用 → 更新初值
- 第三次调用 → 根据当前值进行更新
声明多个状态来单独维护
推荐切分(相关性低的状态)
function testComponent = ()=>{
//声明一个count的state变量
const [count, setCount] = useState(0);
return (
<div>
<p> You clicked {count} times </p>
<button onClick={()=>setCount(count+1)}> + </button>
</div>
)
}
- const [count, setCount] = useState(0);
- count: 当前状态
- setCount: 更新状态的函数
- 0: 初始值
useEffect
- Effect Hook 可以让你在函数组件中执行副作用操作
- 副作用:数据获取、订阅、手动修改DOM
- 用途等同于类组件中componentDidMount, componentDidUpdate,componentWillUnmount和合体
- 类组件有时需要写重复代码
componentDidMount(){ document.title = 'Click here.'; } componentDidUpdate(){ document.title = 'Click here.'; }- 函数组件在每一次渲染之后和每次更新DOM之后都会执行
useEffect(() => { document.title = 'Click here.' });
useReducer
- 区别于useState
- Reducer注重状态变化的过程
- Sate关注状态
- useReducer是useState的替换方案,useReducer更适合管理包含多个值的state对象
const initialState = {count:0};
function reducer(state, action){
switch(action){
case 'increment1':
return {count: state.count + 1};
case 'increment2':
return {count: state.count + 2};
default:
throw new Error();
}
}
function Counter(){
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'increment1'})}>+1</button>
<button onClick={() => dispatch({type: 'increment2'})}>+2</button>
</>
)
}
自定义Hook
- 可以将组件逻辑提取到可重用的函数中,如hooks-useWinSize(实时获取当前浏览器窗口大小)
hooks 规则
- 只能在React函数最顶层调用Hook
- 可以在自定义Hook中调用Hook
- 不能在class组件中使用Hook
- 不能在条件判断或者循环内使用Hook
- 不能在嵌套函数中使用Hook