react-hooks坑

276 阅读1分钟

获取不到最新值

useEffect中的异步获取不到最新值


export default function App() {
  const [count, setCount] = useState(1);

  useEffect(() => {
    const timer = setInterval(() => {
      console.log(count); // 这里永远都是 0
      setCount(count + 1);
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  return (
    <div className="App">
      <h2>{count}</h2>
    </div>
  );
}

原因

// App 第一次执行时的内容
{
    const count = 1
    setInterval(() => {
        console.log(count); // 这里永远都是 0
        setCount(count + 1);
    }, 1000);
}
// App 第二次执行时的内容
{
    const count = 2
}

解决


export default function App() {
  const [count, setCount] = useState(1);

  useEffect(() => {
    const timer = setInterval(() => {
      setCount((count) => {
        console.log(count);
        return count + 1;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  return (
    <div className="App">
      <h2>{count}</h2>
    </div>
  );
}

无限循环

依赖不能是引用类型, setCount触发render -> render触发setCount -> setCount触发render -> render触发setCount -> ...


export default function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    setCount(count + 1); // setCount 会不停的执行
  }, [{}]); // 依赖不能是引用类型

  return (
    <div className="App">
      <h2>{count}</h2>
    </div>
  );
}

hook 不能放在 for if

原因:

  • 每一个 useState 对应一个 hook对象
  • hook的存储方式: fiber.hooks=[hook0, hook1, hook2, ...]
  • 第一个执行的useStatehook0
  • 第二个执行的useStatehook1
  • 如果放到 iffor 中,对应关系将会发生变化, 数据将会错乱

export default function App() {

  if(true) {
    const [count, setCount] = useState(0); // 报错
  }

  for(let i; i<1;i++) {
    const [count, setCount] = useState(0);// 报错
  }

  return (
    <div className="App">
      <h2>{count}</h2>
    </div>
  );
}