这里有个Hooks完全指南

Introduction

One of the main reasons hooks were added to React is to offer a more powerful and expressive way to write (and share) functionality between components
image.png

Hooks allow you to reuse stateful logic without changing your component hierarchy
在几乎所有需要 state 的场景中,都是通过 class components 来作为组件的,因为functional components had no state。 Hooks就是为了更好的使用functional components

State hook(useState())

hooks.gif
上面的动图就表示从标准的 Class components 到 functional components中使用 useState
其中有两点重要的不同:

  • this keyword in function components has been removed (this 被移除)
  • The count state variable hasn’t been defined (state无需定义)

image.png
useState 有两个参数(当前这个名字都是随意取的)

  • The first item of the above array is a variable that gives access to the state value.
  • The second item is a function that updates the state of the component to reflect the new values on the DOM

Effet hook(useEffect())

Class components manage side effects using life cycle methods, like componentDidMount(). The useEffect() function lets you perform side effects in function components (class组件用生命周期方法来处理一些side effects, hooks利用 useEffect 能达到一样的效果)

By default, effects run after every completed render. But, you can choose to fire it only when certain values have changed, passing an array of variables as a second optional parameter
下面是几种useEffect的使用场景

  1. // 1、Without the second parameter
  2. useEffect(() => {
  3. console.log('I will run after every render');
  4. });
  5. // 2、With the second parameter
  6. useEffect(() => {
  7. console.log('I will run only when valueA changes');
  8. }, [valueA]);
  9. // 3、With empty the second parameter
  10. useEffect(() => {
  11. console.log('I will run only once'); // 一次性的买卖,跟componentDidMount类似
  12. }, []);
  13. // 4、With return another function
  14. useEffect(() => {
  15. console.log('I will run only once'); // 一次性的买卖,跟componentDidMount类似
  16. return () => {
  17. // Called just before the component unmount 跟componentDidUnMount类似
  18. console.log('I will be unmounted')
  19. }
  20. }, []);

State management

通过hooks 来实现状态的管理,参考此链接,迷糊是可以看下,比redux, context 操作起来简单很多

Additional Hooks

useReducer

const [state, dispatch] = useReducer(reducer, initialArg, init);
第一个参数是funtion, Accepts a reducer of type (state, action) => newState
第二个参数是指定的初始化状态
第三个参数是懒初始化的function,用在状态的重置上,init函数的参数是 initilaArg 也就是 init(initialArg)
返回值是 第二个参数是 dispatch 方法

useCallback

Pass an inline callback and an array of dependencies. useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders

useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).