React hooks:在监听器中获取 useState 的状态 [英] React hooks: get state of useState inside a listener
问题描述
我的组件中有这个:
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
更新,onSendMessage
中的 pendingMessages
将引用最初存在的相同值.
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
中的值而只想根据先前的值更新状态,因此您可以简单地使用 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屋!