react hook使用

152 阅读2分钟

If you specify a list of dependencies as the last argument to useEffectuseLayoutEffectuseMemouseCallback, or useImperativeHandle, it must include all values that are used inside the callback and participate in the React data flow. That includes props, state, and anything derived from them.

1. effect什么时候会调用?

在每次render时都会调用,而且每次render时调用的effect方法都不一样 it runs both after the first render and after every update

2. React clean up何时调用清除?

在组件卸载时,和再次发生re render后执行下一个effect前

3. 为什么不能在条件语句里使用hook?

react需要确保每次重新渲染时各个hook的调用顺序都是相同的,这样才能将state从正确的hook中取出对应上,条件渲染有可能改变hook调用顺序,导致state在多次渲染中对应不上

4. const [count, setCount] = useState(0)在每次渲染都会执行,但是react能够知道re render时,count的state值

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"  const [count, setCount] = useState(0);

We declare a state variable called count, and set it to 0. React will remember its current value between re-renders, and provide the most recent one to our function. If we want to update the current count, we can call setCount. 我们声明了一个state变量叫做count,并且把它设置为0,在重新渲染之前react将会记住它的当前值,并且提供最近的一个值给到function

You might be wondering: why is useState not named createState instead?Create wouldn’t be quite accurate because the state is only created the first time our component renders. During the next renders, useState gives us the current state. Otherwise it wouldn’t be “state” at all! There’s also a reason why Hook names always start with use. We’ll learn why later in the Rules of Hooks. 为什么不叫createState呢,因为创建state只在第一次渲染时候发生,下次渲染时候useState只是取出当前state的值 We import the useState Hook from React. It lets us keep local state in a function component. 我们import useState从React,它让我们引用state到function内部的变量 When the user clicks, we call setCount with a new value. React will then re-render the Example component, passing the new count value to it. 调用setCount将会重新渲染component

function useDebounce(param, delay) { const [debouncedParam, setDebouncedParam] = useState(param); let timer = null; useEffect(() => { timer = setTimeout(() => { setDebouncedParam(param) }, delay); return () => { clearTimeout(timer) } }, [param, delay]) return debouncedParam }