最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React hooks: get state of useState inside a listener - Stack Overflow

programmeradmin0浏览0评论

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 ]);
}

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?

Thanks!

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 ]);
}

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?

Thanks!

Share Improve this question asked Feb 5, 2019 at 6:27 Mati TucciMati Tucci 2,9766 gold badges30 silver badges42 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 19

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.

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 ]));
}
发布评论

评论列表(0)

  1. 暂无评论