反应useState挂钩未持续更新

时间:2020-04-05 00:15:47

标签: javascript django reactjs websocket react-hooks

我开始将websocket与this example(回购here)一起集成到现有的React / Django应用中。在该存储库中,websocket接口位于websockets.js中,并在containers/Chat.js中实现。

我可以按原样正常工作。

然后我开始重新编写我的实现以使用Hooks,并碰壁了。数据正确地流经套接字,正确地到达每个客户端的处理程序,并且在处理程序内可以读取正确的状态。在该处理程序中,我正在调用useState函数以使用传入的数据更新状态。

最初,我在useState内的单个addMessage()函数出现了不一致的触发问题(十分之一?)。我将一个useState钩子拆分为两个(一个用于当前消息,一个用于所有消息)。现在,在addMessage()中,从服务器接收到数据后,我的setAllMessages钩子将仅更新我在其中键入消息的客户端-没有其他客户端。所有客户端都可以正确接收/记录数据,只是它们没有运行setAllMessages函数。

如果我在函数外部推入一个空数组,它将按预期工作。因此,在函数更新周期中似乎出现了问题,但我无法对其进行跟踪。

这是我的websocket.js版本:

class WebSocketService {
  static instance = null;

  static getInstance() {
    if (!WebSocketService.instance) {
      WebSocketService.instance = new WebSocketService();
    }
    return WebSocketService.instance;
  }

constructor() {
    this.socketRef = null;
    this.callbacks = {};
  }

  disconnect() {
    this.socketRef.close();
  }

  connect(chatUrl) {
    const path = `${URLS.SOCKET.BASE}${URLS.SOCKET.TEST}`;
    this.socketRef = new WebSocket(path);

    this.socketRef.onopen = () => {
      console.log('WebSocket open');
    };

    this.socketRef.onmessage = e => {
      this.socketNewMessage(e.data);
    };

    this.socketRef.onerror = e => {
      console.log(e.message);
    };

    this.socketRef.onclose = () => {
      this.connect();
    };
  }

  socketNewMessage(data) {
    const parsedData = JSON.parse(data);
    const { command } = parsedData;

    if (Object.keys(this.callbacks).length === 0) {
      return;
    }

    Object.keys(SOCKET_COMMANDS).forEach(clientCommand => {
      if (command === SOCKET_COMMANDS[clientCommand]) {
        this.callbacks[command](parsedData.presentation);
      }
    });
  }

  backend_receive_data_then_post_new(message) {
    this.sendMessage({
      command_for_backend: 'backend_receive_data_then_post_new',
      message: message.content,
      from: message.from,
    });
  }

  sendMessage(data) {
    try {
      this.socketRef.send(JSON.stringify({ ...data }));
    } catch (err) {
      console.log(err.message);
    }
  }



 addCallbacks(allCallbacks) {
    Object.keys(SOCKET_COMMANDS).forEach(command => {
      this.callbacks[SOCKET_COMMANDS[command]] = allCallbacks;
    });
  }

  state() {
    return this.socketRef.readyState;
  }
}

const WebSocketInstance = WebSocketService.getInstance();

export default WebSocketInstance;

这是我的Chat.js

export function Chat() {
  const [allMessages, setAllMessages] = useState([]);
  const [currMessage, setCurrMessage] = useState('');

  function waitForSocketConnection(callback) {
    setTimeout(() => {
      if (WebSocketInstance.state() === 1) {
        callback();
      } else {
        waitForSocketConnection(callback);
      }
    }, 100);
  }

  waitForSocketConnection(() => {
    const allCallbacks = [addMessage];
    allCallbacks.forEach(callback => {
      WebSocketInstance.addCallbacks(callback);
    });
  });


/*
 * This is the problem area
 * `incoming` shows the correct data, and I have access to all state
 * But `setAllMessages` only updates on the client I type the message into
 */
  const addMessage = (incoming) => {
    setAllMessages([incoming]);
  };

  // update with value from input
  const messageChangeHandler = e => {
    setCurrMessage(e.target.value);
  };

  // Send data to socket interface, then to server
  const sendMessageHandler = e => {
    e.preventDefault();
    const messageObject = {
      from: 'user',
      content: currMessage,
    };
    setCurrMessage('');
    WebSocketInstance.backend_receive_data_then_post_new(messageObject);
  };

  return (
    <div>
      // rendering stuff here
    </div>
  );
}

1 个答案:

答案 0 :(得分:1)

无需使用钩子将所有内容重写为功能组件。

您应该对其进行功能分解-用于初始化的主(父级,类/ FC),并向负责渲染列表和输入的2个功能性子级/组件提供[数据和]方法(作为道具)(新消息)。

如果您仍然需要... useEffect是一个关键... 所有代码都在功能组件的每个渲染上运行 ... 包括函数定义< / strong>,重新定义,新引用,回调数组中的重复项等。

您可以尝试将所有曾经定义的函数移至useEffect

useEffect(() => {

  const waitForSocketConnection = (callback) => {
    ...
  }

  const addMessage = (incoming) => {
    setAllMessages([incoming]);
  };

  waitForSocketConnection(() => {
    ...
  }

}, [] ); // <<< RUN ONCE