今年以来前端团队推荐使用 hooks,恰逢新开发一个产品,使用了 hooks 体验了一番。
首先要说的 hooks 仅限用于函数组件,那么下面就说说使用频繁的几个。

一、useState

useState 的出现解决了函数组件的 state 使用问题。

1
2
3
4
5
6
7
// 可以直接初始化
const [status, changeStatus] = useState(false)
return (
<div>
<button onClick={() => changeStatus(!status)}>切换</button>
</div>
)

二、useEffect

一般会被认为是 componentDidMount、componentDidUpdate 和 componentwillUnmount 的集合体。
这种说法也不算错。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

useEffect(() => {
// 你关心的异步可以放在这
xxx();
return () => xxx // 你想要想卸载的逻辑
}, []); // 你想多次触发,可以关注下最后这个参数

// or 我可以有多个
useEffect(() => {
// 你关心的异步可以放在这
xxx();
}, []);

useEffect(() => {
return () => xxx // 你想要想卸载的逻辑
}, []);

三、useRef

如果你不想粗暴的去获取 dom,而是更为优雅的使用 dom,你可以试试 useRef,当然如果是 class 组件可以用 createRef

1
2
3
4
// 可以直接初始化
const thisRef = useRef(null);

return <div ref={thisRef}></div>

四、useReducer

1
2
3
4
5
6
7
8
9
10
11
12

const [items, dispatch] = useReducer((state, action)=> {
switch(action.type){
case 'add':
return {
...state,
xxx
}
default:
return state
}
},[])

五、useImperativeHandle/forwardRef

forwardRef 可以暴露整个子组件给父组件

1
2
3
4
5
const ChildForm = forwardRef((props, ref) {
return(
<form ref={ref} {...props}/>
)
});

配合 useImperativeHandle 成对使用的情况下,可以暴露指定的属性或方法给父组件

1
2
3
4
5
6
7
8
9
const ChildForm = forwardRef((props, ref) {
useImperativeHandle(ref, () => ({
getValues: () => {},
param,
}));
return(
<form {...props}/>
)
});

六、memo

memo 函数式组件的优化方法,类似 class 组件中 PureComponent

1
2

const Ele = memo(() => <div ref={thisRef}></div>);

更多的 hooks 就不一一介绍了。

参考:
https://react.docschina.org/docs/hooks-intro.html