React hooks:在侦听器中获取useState状态 [英] React hooks: get state of useState inside a listener

查看:106
本文介绍了React hooks:在侦听器中获取useState状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的组件中有这个:

I have this inside my component:

const [ pendingMessages, setPendingMessages ] = React.useState([]);

React.useEffect(function() {
    ref.current.addEventListener('send-message', onSendMessage);
    return function() {
      ref.current.removeEventListener('send-message', onSendMessage);
    };
  }, []);

function onSendMessage(event) {
  const newMessage = event.message;
  console.log('Here not up to date :(', pendingMessages);
  setPendingMessages([ ...pendingMessages, newMessage ]);
}

问题是 pendingMessages 在监听器内部不是最新的,因为它不是在渲染中。它已经附加了。任何想法我该如何解决这个问题?

The problem is that pendingMessages is not up to date inside the listener because it's not inside the render. It's already attached. Any ideas how can I resolve this?

谢谢!

推荐答案

问题是由于在运行效果时形成了一个关闭。因为你设置 useEffect 只在初始安装时运行,它从声明它时形成的闭包中获取 pendingMessages 的值,因此即使 pendingMessages 更新, pendingMessages onSendMessage 内将引用最初存在的相同值。

The problem is because of a close that is formed when the effect is run. Since you set the useEffect to run only on initial mount, it gets the value of pendingMessages from the closure that is formed when it is declared and hence even if the the pendingMessages updates, pendingMessages inside onSendMessage will refer to the same value that was present initially.

因为您不想访问 onSendMessage 中的值,只需根据之前的va更新状态lue,你可以简单地使用setter的回调模式

Since you do not want to access the value in onSendMessage and just update the state based on previous value, you could simply use the callback pattern of setter

const [ pendingMessages, setPendingMessages ] = React.useState([]);

React.useEffect(function() {
    ref.current.addEventListener('send-message', onSendMessage);
    return function() {
      ref.current.removeEventListener('send-message', onSendMessage);
    };
  }, []);

function onSendMessage(event) {
  const newMessage = event.message;
  setPendingMessages(prevState =>([ ...prevState, newMessage ]));
}

这篇关于React hooks:在侦听器中获取useState状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆