带有useState的数组不更新websocket函数内的值

时间:2020-12-31 18:34:43

标签: reactjs react-hooks

我试图在浏览器中发生事件时更改数组的状态,特别是在触发 websocket 时,问题是我的数组保持原始状态并且永不改变。感谢您的帮助

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

当浏览器中的某个事件(电缆)发生时会触发函数handleReceiveNewName,但是当我想访问console.log中的值时,“hello”永远不会被添加

1 个答案:

答案 0 :(得分:1)

将新数组直接传递给函数,而不是函数返回新数组

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