hushicai / hushicai.github.io

Blog
https://hushicai.github.io
27 stars 1 forks source link

React Hooks #64

Open hushicai opened 5 years ago

hushicai commented 5 years ago

官方文档

hushicai commented 5 years ago

Hooks FAQ

hushicai commented 5 years ago

A Complete Guide to useEffect

hushicai commented 5 years ago

精读《useEffect 完全指南》

hushicai commented 5 years ago

Making Sense of React Hooks

hushicai commented 5 years ago

数据为何不是最新的?

function Example() {
  const [count, setCount] = useState(0);

  function handleAlertClick() {
    setTimeout(() => {
      alert('You clicked on: ' + count);
    }, 3000);
  }

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
      <button onClick={handleAlertClick}>
        Show alert
      </button>
    </div>
  );
}

演示步骤:

  1. 点击Show alerthandleAlertClick将在3s后弹出提示

  2. 在弹出提示之前,快速点击Click me,递增count值。

  3. 3s后看到的count提示仍为0。

这就是Dan Abramov在A Complete Guide to useEffect中提到的,每一次渲染都有自己的快照,每一次渲染都有自己的effect、callback等,React自动捕获了闭包变量。

示例:https://hulde.codesandbox.io/

hushicai commented 5 years ago

如何获取最新数据?

官方建议通过ref来解决。

function Example() {
  const ref = useRef(0);
  const [count, setCount] = useState(0);

  const handleAlertClick = useCallback(() => {
    setTimeout(() => {
      alert("You clicked on: " + ref.current);
    }, 3000);
  }, []);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button
        onClick={() => {
          ref.current = count + 1;
          setCount(count + 1);
        }}
      >
        Click me
      </button>
      <button onClick={handleAlertClick}>Show alert</button>
    </div>
  );
}

ref是一个可变的数据容器,通常是用来存储组件实例或者DOM元素引用,但也可以存放任何类型数据。

示例:https://h7h06.codesandbox.io/

hushicai commented 4 years ago

React hooks: not magic, just arrays

hushicai commented 4 years ago

Deep dive: How do React hooks really work?

hushicai commented 4 years ago

Under the hood of React’s hooks system