React hooks: get state of useState inside a listener

前端 未结 1 874
予麋鹿
予麋鹿 2020-12-30 14:46

I have this inside my component:

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

React.useEffect(function() {
    ref.current.addEventLi         


        
1条回答
  •  有刺的猬
    2020-12-30 15:39

    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 讨论(0)
提交回复
热议问题