简体   繁体   English

具有 useState 的数组未更新 websocket function 内的值

[英]Array with useState not updating value inside websocket function

I am trying to change the state of an array when an event happens in the browser, specifically when the websocket is triggered, the problem is that my array keeps the original state and never changes.我正在尝试在浏览器中发生事件时更改数组的 state,特别是在触发 websocket 时,问题是我的数组保留了原始 state 并且永远不会更改。 Thanks for your help谢谢你的帮助

  export default function StreamPanel(){

   const [streamsNotRead, setStreamsNotRead] = useState(["bye"]);

   function costumerInfo () {
        return new Promise(resolve => {
        setTimeout(() => { 
    
        const cable = ActionCable.createConsumer(`wss:/aplace`)
        const sub = cable.subscriptions.create('SomeChannel', {
          received: handleReceiveNewName
        })
        handleClose()
        resolve()   
      },3000);
    });
      }

   const handleReceiveNewName = m => {
        setStreamsNotRead(streamsNotRead => [...streamsNotRead, "hello" ]);
        console.log(streamsNotRead)
   }

   return(</div>)
}

The function handleReceiveNewName is triggered when a certain event (the cable) in the browser happens, but when I want to access the value in the console.log "hello" is never added当浏览器中的某个事件(电缆)发生时,会触发 function handleReceiveNewName,但是当我想访问 console.log 中的值时,永远不会添加“hello”

Pass the new array directly to the function instead of a function returning the new array将新数组直接传递给 function 而不是 function 返回新数组

const handleReceiveNewName = m => {
    setStreamsNotRead([...streamsNotRead, "hello" ]);
    console.log(streamsNotRead)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM