首页 > 解决方案 > 使用 React 钩子时获取最新状态值的正确方法

问题描述

我对 React hooks API 相当陌生,在实现我的应用程序时遇到了 Stale 闭包问题。实现 UseEffect API 以获取最新状态值是可行的,但在事件驱动的流程中,检索最新状态值的最佳方法是什么。有关详细信息,请查看以下代码段 -

allParticipants变量使用react-redux useSelectorAPI 捕获值 -

  const allParticipants = useSelector((state) => {
    return state.participants;
  });

这里注册了一个事件处理程序,以便在触发特定事件时调用 -

  async function createPeerConnection(pcIndex) {
    console.log(`:: createPeerConnection ::  for ${pcIndex}`);
    try {
      const peerConnection = new RTCPeerConnection(pcConfig);
      peerConnection.onnegotiationneeded = (event) => handleNegotiationNeeded(pcIndex, event);
  function handleNegotiationNeeded(pcIndex, event) {
    console.log(`:: handleNegotiationNeeded  for index ${pcIndex}::`);
    const requestTo = allParticipants[pcIndex].id

handleNegotiation 函数需要 allParticipants 状态的最新值,该状态在调用该函数之前已更新,但它保存状态的初始值,我认为这是陈旧的闭包问题。我不能在useEffects这里使用 API,因为触发事件时会调用该函数。这样做的正确方法是什么?

标签: reactjsreact-reduxreact-hooks

解决方案


推荐阅读