如何在触发 useEffect 钩子之前等待来自 redux 存储的数据?

时间:2021-03-22 02:14:34

标签: node.js reactjs redux react-redux socket.io

我目前正在开发一个使用 React、Redux 和 Socket.io 的应用程序。当用户登录并进入消息页面时,套接字和房间就按照它应该的方式创建。但是,当我单击刷新时,似乎我的 useEffect 函数在从 redux 存储接收数据之前触发,该函数正确设置了套接字和房间。有没有人遇到过这样的问题?如果是这样,你如何解决它?提前致谢

编辑: 刚刚尝试使用 setTimeout() 并仍然产生相同的结果。我很茫然。任何帮助将不胜感激

代码如下:

import Sidebar from './Sidebar';
import { Container, Col, Row, Card } from 'react-bootstrap';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { receiveMessage } from '../../actions/conversation';
//Socket.IO import
import io from 'socket.io-client';

const Messenger = ({ auth, receiveMessage }) => {
  const [socket, setSocket] = useState(null);

  const setupSocket = () => {
    const id = auth.userNumber;
    console.log('fdhsafidhsafkdjsafhdusafhdsafidgsafdusa', id);
    if (!socket) {
      const newSocket = io('http://localhost:5000', {
        query: {
          id: id,
        },
      });

      newSocket.on('disconnect', () => {
        setSocket(null);
        setTimeout(setupSocket, 3000);
      });

      newSocket.on('receive-message', (message) => {
        console.log('socket.io-client message', message);
        receiveMessage(message);
      });
    }
    // return () => newSocket.close();
  };

  useEffect(async () => {
    await setupSocket();   <=== Problem is here
  }, []);
return (
    <div>
      <Sidebar />
    </div>
  );
};

Messenger.propTypes = {
  auth: PropTypes.object.isRequired,
  receiveMessage: PropTypes.func.isRequired,
};

const mapStateToProps = (state) => ({
  auth: state.auth,
});

export default connect(mapStateToProps, { receiveMessage })(Messenger);```

1 个答案:

答案 0 :(得分:0)

事实证明,套接字本质上会在刷新时被破坏。转到此处了解更多信息:Keep WebSocket connection alive after refresh