# 介绍
向下兼容
React从16.8之后支持Hook,官方虽说Hook是100%向后兼容,完全可选,没有计划移出class等一系列说辞,但是官方越来越靠近Hook,新项目开发建议直接使用Hook,老项目开发不建议重构
优点
更简洁,维护更方便
规律
Hook都是以use开头
# useState
介绍
useState是状态管理的偷懒方式,让无状态组件(后官方更名为函数组件)能像有状态组件一样使用状态管理
使用
引用简单变量,更新状态可以直接传值
import React, { useState } from 'react';
function App() {
const [number, setNumber] = useState(1);
return (
<div>
<button onClick={() => setNumber(number + 1)}>+ 1</button>
<span>{number}</span>
<button onClick={() => setNumber(number - 1)}>- 1</button>
</div>
)
}
export default App;
更新状态可以直接传函数
import React, { useState } from 'react';
function App() {
const [number, setNumber] = useState(1);
const changeNumber = (num) => {
setNumber(() => num);
}
return (
<div>
<button onClick={() => changeNumber(number + 1)}>+ 1</button>
<span>{number}</span>
<button onClick={() => changeNumber(number - 1)}>- 1</button>
</div>
)
}
export default App;
如果是对象,状态不会合并,注意状态丢失
import React, { useState } from 'react';
function App() {
const [stu, setStu] = useState({ name: "张三", age: 12 });
return (
<div>
<span>{stu.name}-{stu.age}</span>
<button onClick={() => setStu({ ...stu, age: 18 })}>长大</button>
</div>
)
}
export default App;
如果是数组,处理比较复杂可以在函数中处理
import React, { useState } from 'react';
function App() {
const [arr, setArr] = useState([1, 2, 3, 4]);
const changeArr = () => {
arr.splice(0, 2, ["一", "二"]);
setArr(arr);
}
return (
<div>
<span>{arr}</span>
<button onClick={() => changeArr()}>变化</button>
</div>
)
}
export default App;
# useEffect
介绍
useEffect是生命周期的偷懒方式,让无状态组件能像有状态组件一样使用生命周期
useEffect可以看做是componentDidMount(DOM挂载完成),componentDidUpdate(组件更新) 和 componentWillUnmount(组件销毁)的组合
但实际上,useEffect比有状态组件的生命周期性能更高,使用 useEffect 调度的 effect 不会阻塞浏览器更新屏幕,这让你的应用看起来响应更快
状态
useEffect可以直接调用状态的值
useEffect调用状态是实时更新的,并不是一成不变
使用
语法:useEffect(fn,arr:Array?)
只有回调函数
会在DOM挂载完成时调用一次(官方说法第一次渲染之后),组件每次更新时调用
以下代码刚开始触发打印,之后每次操作都会触发
import React, { useState, useEffect } from 'react';
function App() {
const [number, setNumber] = useState(1);
useEffect(() => {
console.log(1);
});
return (
<div>
<button onClick={() => setNumber(number + 1)}>+ 1</button>
<span>{number}</span>
<button onClick={() => setNumber(number - 1)}>- 1</button>
</div>
)
}
export default App;
第二个参数为空时,状态更新不会触发回调函数,但初始时会触发一次
import React, { useState, useEffect } from 'react';
function App() {
const [number, setNumber] = useState(1);
useEffect(() => {
console.log(number);
}, []);
return (
<div>
<button onClick={() => setNumber(number + 1)}>+ 1</button>
<span>{number}</span>
<button onClick={() => setNumber(number - 1)}>- 1</button>
</div>
)
}
export default App;
第二个参数的数组中可以传入状态,那么此状态的更新就会触发回调函数
import React, { useState, useEffect } from 'react';
function App() {
const [number, setNumber] = useState(1);
useEffect(() => {
console.log(number);
}, [number]);
return (
<div>
<button onClick={() => setNumber(number + 1)}>+ 1</button>
<span>{number}</span>
<button onClick={() => setNumber(number - 1)}>- 1</button>
</div>
)
}
export default App;
useEffect可以设置多个
import React, { useState, useEffect } from 'react';
function App() {
const [number, setNumber] = useState(1);
useEffect(() => {
console.log(number);
}, [number]);
useEffect(() => {
console.log(number);
}, []);
return (
<div>
<button onClick={() => setNumber(number + 1)}>+ 1</button>
<span>{number}</span>
<button onClick={() => setNumber(number - 1)}>- 1</button>
</div>
)
}
export default App;
useEffect的回调函数中返回一个函数,这个函数在组件移除时调用。这个函数主要处理移除DOM侦听,清空定时器,清除订阅等
import React, { useState, useEffect } from 'react';
function App() {
const [number, setNumber] = useState(1);
useEffect(() => {
return () => {
// 清除侦听 订阅 定时器等
}
});
return (
<div>
<button onClick={() => setNumber(number + 1)}>+ 1</button>
<span>{number}</span>
<button onClick={() => setNumber(number - 1)}>- 1</button>
</div>
)
}
export default App;
# useRef
介绍
可以获取DOM,可以存储变量
使用
必须通过 useRef 初始化一个值,这个值要绑定到需要获取的标签上
可以用 current 来获取绑定的DOM
import React, { useRef } from 'react';
function App() {
const h1El = useRef(null);
const log = () => {
console.log(h1El.current);
}
return (
<div>
<h1 ref={h1El}>Hello React!</h1>
<button onClick={() => log()}>Get Ele</button>
</div>
)
}
export default App;
useRef如果有传入值,且不绑定ref,则 current 就不是获取DOM,而是初始的对象
import React, { useRef } from 'react';
function App() {
const h1El = useRef({ name: "张三" });
const log = () => {
console.log(h1El); // { current: {name: "张三"} }
}
return (
<div>
<h1>Hello React!</h1>
<button onClick={() => log()}>Get Ele</button>
</div>
)
}
export default App;
# useContext
介绍
上下文的Hook,方便上游组件像下游组件传值
使用
必须配合 createContext
当上游状态变化时,下游也会发生变化
import React, { useContext, createContext, useState } from 'react';
function App() {
const MyContent = createContext();
const [number, setNumber] = useState(0);
const C1 = () => {
let number = useContext(MyContent);
return (
<div>
<p>子组件1</p>
<p>{number}</p>
<hr />
</div>
);
}
const C2 = () => {
let number = useContext(MyContent);
return (
<div>
<p>子组件2</p>
<p>{number}</p>
</div>
);
}
return (
<div>
<MyContent.Provider value={number}>
<h2>父组件{number}</h2>
<hr />
<C1></C1>
<C2></C2>
</MyContent.Provider>
</div>
)
}
export default App;
如果把父组件中更新状态的方法也传给子组件,那么子组件也能更新父组件状态
import React, { useContext, createContext, useState } from 'react';
function App() {
const MyContent = createContext();
const [number, setNumber] = useState(0);
const C1 = () => {
const { number, setm } = useContext(MyContent);
return (
<div>
<p>子组件1</p>
<p>{number}</p>
<button onClick={() => setm(number - 1)}> - 1</button>
</div>
);
}
return (
<div>
<MyContent.Provider value={{ number, setm: setNumber }}>
<h2>父组件{number}</h2>
<button onClick={() => setNumber(number + 1)}> + 1</button>
<C1></C1>
</MyContent.Provider>
</div>
)
}
export default App;
拆分
// ./src/App.js
import React, { useState } from 'react';
import MyContent from './MyContent/index';
import C1 from "./c1"
function App() {
const [number, setNumber] = useState(0);
return (
<div>
<MyContent.Provider value={number}>
<h2>父组件{number}</h2>
<button onClick={() => setNumber(number + 1)}> + 1</button>
<C1></C1>
</MyContent.Provider>
</div>
)
}
export default App;
// ./MyContent/index.js
import { createContext } from 'react';
const MyContent = createContext();
export default MyContent;
// ./src/c1.js
import React, { useContext } from 'react';
import MyContent from './MyContent/index';
export default function C1() {
const number = useContext(MyContent);
return (
<div>
<p>子组件1</p>
<p>{number}</p>
</div>
)
}
# useMemo
触发时机
useMemo 是在状态更新时触发,useEffect 是在组件渲染后触发
import React, { useMemo, useEffect, useState } from 'react';
function App() {
const [number, setNumber] = useState(0);
useEffect(() => console.log(`useEffect`));
useMemo(() => console.log(`useMemo`));
console.log("render");
return (
<div>
<h1>{number}</h1>
<button onClick={() => setNumber(number + 1)}>+ 1</button>
</div>
)
}
export default App;
以上代码会依次打印:useMemo render useEffect
语法
和 useEffect 相同, 可以接收两个参数
参数一:回调函数,初始和每次侦听的状态变化时执行
参数二(可选):如果不传,侦听所有状态变化。空数组,不侦听所有变化。数组,列举侦听的状态
import React, { useMemo, useState } from 'react';
function App() {
const [number, setNumber] = useState(0);
useMemo(
() => {
console.log(`useMemo`);
}, [number]);
return (
<div>
<h1>{number}</h1>
<button onClick={() => setNumber(number + 1)}>+ 1</button>
</div>
)
}
export default App;
用法
返回一个新状态,并可以在 render 中渲染这个状态
import React, { useMemo, useState } from 'react';
function App() {
const [number, setNumber] = useState(0);
let newNumber = useMemo(
() => {
return number;
}, [number]);
return (
<div>
<h1>{newNumber}</h1>
<button onClick={() => setNumber(newNumber + 1)}>+ 1</button>
</div>
)
}
export default App;
使用场景
避免重复渲染
import React, { useState } from 'react';
function App() {
const [number1, setNumber1] = useState(0);
const [number2, setNumber2] = useState(0);
const num2 = 10;
const count = () => {
console.log(1);
return num2 + number1;
}
return (
<div>
<h1>{count()}</h1>
<button onClick={() => setNumber1(number1 + 1)}>changeNumber1</button>
<button onClick={() => setNumber2(number2 + 1)}>changeNumber2</button>
</div>
)
}
export default App;
我们看到,无论 number1 还是 number2 更新,count 函数都会重新执行,但是 count 只与 number1 有关
import React, { useState,useMemo } from 'react';
function App() {
const [number1, setNumber1] = useState(0);
const [number2, setNumber2] = useState(0);
const num2 = 10;
const count = useMemo(()=>{
console.log(1);
return num2 + number1;
},[number1])
return (
<div>
<h1>{count}</h1>
<button onClick={() => setNumber1(number1 + 1)}>changeNumber1</button>
<button onClick={() => setNumber2(number2 + 1)}>changeNumber2</button>
</div>
)
}
export default App;
使用useMemo以后,只有当指定状态更新,才会重新计算
说明
useMemo 和 shouldComponentUpdate 类似,为了避免组件重复渲染,提高性能
useMemo 利用了 JavaScript 的缓存技术 memoization
# useCallback
作用
避免组件重新渲染,提高性能(和 useMemo 相同)
和useMemo不同的地方是 useCallback 返回的是函数
import React, { useState, useCallback } from 'react';
function App() {
const [number, setNumber] = useState(0);
const count = useCallback(()=>{
return number;
},[number])
return (
<div>
<h1>{count()}</h1>
<button onClick={() => setNumber(number + 1)}>changeNumber1</button>
</div>
)
}
export default App;
# useLayoutEffect
介绍
和 useEffect 语法相同,但是会阻塞视觉更新
如果能用 useEffect 就尽量避免使用 useLayoutEffect ,除非遇到BUG或解决不了的问题
触发时机
先于 useEffect 执行,即使组件销毁时,也先于 useEffect 执行
useLayoutEffect 调用时机为componentDidMount、componentDidUpdate
import React, { useEffect,useLayoutEffect } from 'react';
function App() {
useEffect(()=> console.log(`useEffect`))
useLayoutEffect(()=> console.log(`useLayoutEffect`))
return (
<>
<h1>hello React!</h1>
</>
)
}
export default App;
# 自定义Hook
简介
就是普通函数,但是必须以use开头
做一些封装,方便使用
内部可以使用其他Hook
封装
例一:定义一个Hook,每次对相应的值 + 2
import React, { useState } from 'react';
function App() {
const useCount = (count, val) => {
const [number, setNumber] = useState(count);
const add = () => setNumber(number + val);
return { number, add };
}
const { number, add } = useCount(10, 2);
return (
<>
{number}
<h1>hello React!</h1>
<button onClick={() => add()}>增加</button>
</>
)
}
export default App;
例二:定义一个Hook,返回的方法可以得到当前变量的阶和
import React, { useState } from 'react';
function App() {
const useCount = (index) => {
const comp = (number) => number * (number + 1) / 2;
const [number, setNumber] = useState(index);
const [count, setCount] = useState(comp(index));
const add = () => {
setNumber(number + 1);
setCount(comp(number + 1));
}
return { number, add, count }
}
const { number, add, count } = useCount(0);
return (
<>
<p>下标:{number}</p>
<p>阶和:{count}</p>
<h1>hello React!</h1>
<button onClick={() => add()}>增加</button>
</>
)
}
export default App;
# useImperativeHandle
简介
可以在使用 ref 时自定义暴露给父组件的实例值
应避免使用 ref ,useImperativeHandle 要与 forwardRef 一起使用
forwardRef
我们先看一下,普通获取 ref 的情况
import React, { useRef } from 'react';
const C1 = () => {
return (
<div>
<h1>子组件1</h1>
<p>hello world!</p>
</div>
)
}
function App() {
const ref = useRef(null);
return (
<>
<C1 ref={ref}></C1>
<button onClick={() => { console.log(ref) }}>获取ref</button>
</>
)
}
export default App;
此时点击按钮时,获取到了h1的DOM
我们再来看一下组件时的情况
import React, { useRef } from 'react';
function App() {
const ref = useRef(null);
const C1 = () => {
return (
<div>
<h1>子组件1</h1>
<p>hello world!</p>
</div>
)
}
return (
<>
<C1 ref={ref}></C1>
<button onClick={() => { console.log(ref) }}>获取ref</button>
</>
)
}
export default App;
此时点击按钮时,获取的 DOM 为 null
而如果想获取组件内部的DOM,则必须把 ref 传到组件内部(注意不能用 ref,因为 props 不解析 ref)
import React, { useRef } from 'react';
const C1 = ({ Ref }) => {
return (
<div>
<h1 ref={Ref}>子组件1</h1>
<p>hello world!</p>
</div>
)
}
function App() {
const ref = useRef(null);
return (
<>
<C1 Ref={ref}></C1>
<button onClick={() => { console.log(ref) }}>获取ref</button>
</>
)
}
export default App;
此时点击按钮时,就获取了子组件的 DOM
获取子组件的 DOM ,还有另一种写法,就是forwardRef , 可以直接写 ref
import React, { useRef, forwardRef } from 'react';
const C1 = forwardRef((props, ref) => {
return (
<div>
<h1 ref={ref}>子组件1</h1>
<p>hello world!</p>
</div>
)
})
function App() {
const ref = useRef(null);
return (
<>
<C1 ref={ref}></C1>
<button onClick={() => { console.log(ref) }}>获取ref</button>
</>
)
}
export default App;
官方更推荐这种写法,此时 ref 不需要更名也能被读取
useImperativeHandle使用
如果父组件不想获取子组件的 DOM 而是方法和属性呢?就需要使用 useImperativeHandle
import React, { useRef, forwardRef, useImperativeHandle } from 'react';
const C1 = forwardRef((props, ref) => {
useImperativeHandle(ref, () => {
return { name: "张三" }
})
return (
<div>
<h1 ref={ref}>子组件1</h1>
<p>hello world!</p>
</div>
)
})
function App() {
const ref = useRef(null);
return (
<>
<C1 ref={ref}></C1>
<button onClick={() => { console.log(ref) }}>获取ref</button>
</>
)
}
export default App;
当然,用另一种方式也可,(不推荐)
import React, { useRef, useImperativeHandle } from 'react';
const C1 = ({ Ref }) => {
useImperativeHandle(Ref, () => {
return { name: "张三" }
})
return (
<div>
<h1>子组件1</h1>
<p>hello world!</p>
</div>
)
}
function App() {
const ref = useRef(null);
return (
<>
<C1 Ref={ref}></C1>
<button onClick={() => { console.log(ref) }}>获取ref</button>
</>
)
}
export default App;
第三个参数表示侦听状态的变化,如果状态无变化,则参数二返回的值无更新
import React, { useRef, useImperativeHandle, useState } from 'react';
const C1 = ({ Ref }) => {
const [num1, setNum1] = useState(0);
const [num2, setNum2] = useState(0);
useImperativeHandle(Ref, () => {
return { num1 }
}, [num2])
return (
<div>
<p>{num1}</p>
<p>{num2}</p>
<button onClick={() => setNum1(num1 + 1)}>c 1</button>
<button onClick={() => setNum2(num2 + 1)}>c 2</button>
</div>
)
}
function App() {
const ref = useRef(null);
return (
<>
<C1 Ref={ref}></C1>
<button onClick={() => { console.log(ref) }}>获取ref</button>
</>
)
}
export default App;
当点击c1 5下,再点击获取 ref 时,num1 为0,再点击 c2 一次,再点击获取 ref 时,num1 为 5
# useReducer
介绍
useReducer 和 redux 中的 Reducer 是一样的,是一个函数
useReducer 是 useState 的替代方案,某些场景比 useState 更适用
useReducer 返回值是一个数组,第一个参数是状态 state ,第二个参数是分发 dispatch
使用
使用方式和 redux 一样,接收三个参数,前两个分别是 reduce 和初始状态 state
import React, { useReducer } from 'react';
function App() {
const reducer = (state, action) => {
switch (action.type) {
case `changeName`:
return { ...state, name: action.payload }
case `changeAge`:
return { ...state, age: action.payload }
default:
return state;
}
}
const data = { name: "张三", age: 12 };
const [state, dispatch] = useReducer(reducer, data);
return (
<>
<h2>{state.name} --- {state.age}</h2>
<button onClick={() => dispatch({ type: "changeName", payload: "李四" })}>切换名称</button>
<button onClick={() => dispatch({ type: "changeAge", payload: 18 })}>切换年龄</button>
</>
)
}
export default App;
结合 useContext 实现 redux 的功能
抽离 redux
import React, { createContext, useReducer } from 'react'
const stateInit = {
name: "张三",
age: 14
}
const reduce = (state, action) => {
switch (action.type) {
case "changName":
return { ...state, name: action.payload }
case "changAge":
return { ...state, age: action.payload }
default:
return state;
}
}
const MyContext = createContext();
export { MyContext };
export default (props) => {
const [state, dispatch] = useReducer(reduce, stateInit);
return (
<MyContext.Provider value={{ state, dispatch }}>
{props.children}
</MyContext.Provider>
)
}
实现 redux
import React, { useContext } from 'react';
import MyRedux, { MyContext } from "./MyRedux"
const C1 = () => {
const { state, dispatch } = useContext(MyContext);
return (
<>
<p>子组件C1</p>
<p>{state.name}---{state.age}</p>
<button onClick={() => dispatch({ type: "changName", payload: "李四" })}>更新名称</button>
<button onClick={() => dispatch({ type: "changAge", payload: 16 })}>更新年龄</button>
</>
)
}
const C2 = () => {
const { state, dispatch } = useContext(MyContext);
return (
<>
<p>子组件C2</p>
<p>{state.name}---{state.age}</p>
<button onClick={() => dispatch({ type: "changName", payload: " 张三" })}>更新名称</button>
<button onClick={() => dispatch({ type: "changAge", payload: 15 })}>更新年龄</button>
</>
)
}
function App() {
return (
<>
<MyRedux>
<C1></C1>
<hr />
<C2></C2>
</MyRedux>
</>
)
}
export default App;
下一篇:redux篇