相关疑难解决方法(0)

为什么需要useRef在组件函数之外包含可变变量而不定义变量?

我已阅读了《使用效果的完全指南-过度反应应对潮流》

该示例表明,如果我们想获取最新的count,我们可以useRef用来保存可变变量,并在异步函数laster中获取它:

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

  useEffect(() => {
    // Set the mutable latest value
    latestCount.current = count;
    setTimeout(() => {
      // Read the mutable latest value
      console.log(`You clicked ${latestCount.current} times`);
    }, 3000);
  });
  // ...
}
Run Code Online (Sandbox Code Playgroud)

但是,我可以通过在组件函数外部创建一个变量来执行相同的操作,例如:

import React, { useState, useEffect, useRef } from 'react';

// defined a variable outside function component
let countCache = 0;

function Counter() {
  const [count, setCount] = useState(0); …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks

2
推荐指数
2
解决办法
139
查看次数

标签 统计

react-hooks ×1

reactjs ×1