React 钩子:从回调中访问最新状态

新手上路,请多包涵

编辑(2020 年 6 月 22 日):由于这个问题重新引起了人们的兴趣,我意识到可能存在一些困惑。所以我想强调:问题中的例子只是一个玩具例子。它不能反映问题。引发这个问题的问题是使用第三方库(对其控制有限),该库将回调作为函数的参数。为该回调提供最新状态的正确方法是什么。在 React 类中,这将通过使用 this 来完成。在 React hooks 中,由于状态被封装在 React.useState() 函数中的方式,如果回调通过 React.useState() 获取 状态,它将过时(设置回调时的值).但是如果它 设置 了状态,它将可以通过传递的参数访问最新的状态。这意味着我们可以通过将状态 设置 为与之前相同的状态来使用 React hooks 在此类回调中获得最新状态。这有效,但违反直觉。

-- 原始问题在下面继续 –

我正在使用 React 挂钩并尝试从回调中读取状态。每次回调访问它时,它都会回到默认值。

使用以下代码。无论我点击多少次,控制台都会继续打印 Count is: 0

 function Card(title) {
  const [count, setCount] = React.useState(0)
  const [callbackSetup, setCallbackSetup] = React.useState(false)

  function setupConsoleCallback(callback) {
    console.log("Setting up callback")
    setInterval(callback, 3000)
  }

  function clickHandler() {
    setCount(count+1);
    if (!callbackSetup) {
      setupConsoleCallback(() => {console.log(`Count is: ${count}`)})
      setCallbackSetup(true)
    }
  }


  return (<div>
      Active count {count} <br/>
      <button onClick={clickHandler}>Increment</button>
    </div>);

}

const el = document.querySelector("#root");
ReactDOM.render(<Card title='Example Component' />, el);

你可以 在这里 找到这段代码

我在回调中设置状态没有问题,只是在访问最新状态时。

如果让我猜一猜,我会认为任何状态的改变都会创建 Card 函数的一个新实例。并且回调指的是旧回调。根据 https://reactjs.org/docs/hooks-reference.html#functional-updates 上的文档,我想到了在回调中调用 setState 并将函数传递给 setState 的方法,看看是否我可以从 setState 中访问当前状态。更换

setupConsoleCallback(() => {console.log(`Count is: ${count}`)})

setupConsoleCallback(() => {setCount(prevCount => {console.log(`Count is: ${prevCount}`); return prevCount})})

你可以 在这里 找到这段代码

这种方法也没有奏效。编辑:实际上第二种方法 确实 有效。我只是在我的回调中有一个错字。这是正确的做法。我需要调用 setState 来访问之前的状态。尽管我无意设置状态。

我觉得我对 React 类采取了类似的方法,但是。为了代码的一致性,我需要坚持使用 React Effects。

如何从回调中访问最新的状态信息?

原文由 rod 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 755
2 个回答

对于您的场景(您不能继续创建新的回调并将它们传递给您的第 3 方库),您可以使用 useRef 使可变对象保持当前状态。像这样:

 function Card(title) {
  const [count, setCount] = React.useState(0)
  const [callbackSetup, setCallbackSetup] = React.useState(false)
  const stateRef = useRef();

  // make stateRef always have the current count
  // your "fixed" callbacks can refer to this object whenever
  // they need the current value.  Note: the callbacks will not
  // be reactive - they will not re-run the instant state changes,
  // but they *will* see the current value whenever they do run
  stateRef.current = count;

  function setupConsoleCallback(callback) {
    console.log("Setting up callback")
    setInterval(callback, 3000)
  }

  function clickHandler() {
    setCount(count+1);
    if (!callbackSetup) {
      setupConsoleCallback(() => {console.log(`Count is: ${stateRef.current}`)})
      setCallbackSetup(true)
    }
  }

  return (<div>
      Active count {count} <br/>
      <button onClick={clickHandler}>Increment</button>
    </div>);

}

您的回调可以引用可变对象来“读取”当前状态。它将在其闭包中捕获可变对象,并且每次渲染可变对象时都将使用当前状态值进行更新。

原文由 Brandon 发布,翻译遵循 CC BY-SA 4.0 许可协议

2021 年 6 月更新:

使用 NPM 模块 react-usestateref 始终获取最新的状态值。它完全向后兼容 React useState API。

示例代码如何使用它:

 import useState from 'react-usestateref';

const [count, setCount, counterRef] = useState(0);

console.log(couterRef.current); // it will always have the latest state value
setCount(20);
console.log(counterRef.current);

NPM 包 react-useStateRef 允许您使用 useState 访问最新状态(如 ref )。

2020 年 12 月更新:

为了准确解决这个问题,我为此创建了一个反应模块。 react-usestateref (反应 useStateRef)。使用示例:

 var [state, setState, ref] = useState(0);

它的工作原理很像 useState 但除此之外,它还为您提供 ref.current 下的当前状态

学到更多:

原始答案

您可以使用 setState 获取最新值

例如:

 var [state, setState] = useState(defaultValue);

useEffect(() => {
   var updatedState;
   setState(currentState => { // Do not change the state by getting the updated state
      updateState = currentState;
      return currentState;
   })
   alert(updateState); // the current state.
})

原文由 Aminadav Glickshtein 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题