首页 > 解决方案 > 即使我设置了它,我的 usestate 也没有更新

问题描述

我正在打印stream变量,但null在更新它之后我什至得到了。

当我的设置状态被调用时,我应该重新渲染整个组件吗?由于此代码执行一次,如果是这样,该怎么做?

const [stream, setStream] = useState(null);

async function getLocalStream() {
  let isFront = true;

  const devices = await mediaDevices.enumerateDevices();
  if (!stream) {
    let s;
    try {
      s = await mediaDevices.getUserMedia({
        audio: true,
        video: true,
      });
      setStream(s); //here i am setting my state
    } catch (e) {
      console.error(e);
    }
  }
}

useEffect(() => {
  socket.current = io.connect('http://192.8.1.13:3001');
  socket.current.emit('new-room', route.params.roomid, route.params.name);

  socket.current.on('room-created', async (id, roomid, name) => {
    getLocalStream(); // calling function
  });

  socket.current.on('join-room', async (id, roomid, name) => {
    getLocalStream();
  });

  socket.current.on('new-user', async (id, roomid, name) => {
    console.log('stream', stream); // my value is always null
  });
}, []);

标签: reactjsreact-nativereact-reduxreact-hooks

解决方案


推荐阅读