Heim  >  Fragen und Antworten  >  Hauptteil

Von socket.io empfangene Daten spiegeln sich nicht sofort im Status wider

Wenn app.js接收到从服务器发送的数据(在控制台中显示),setState不会使用新数据刷新网页。在console.log("Received data queue:", data.queue)的行中,它也返回undefined。我期望它是一个特定的值,因为在console.log(data) in einer Zeile steht, wird der Wert unter der „Warteschlange“-Taste gespeichert.

Das ist mein Code:

import React, { Component } from "react";
import { TransitionGroup, CSSTransition } from "react-transition-group";
import "./chat.css";
import "./styles.css";
import "./queue.css";
import Chat from "./chat";
import io from "socket.io-client";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      queue: [],
      instruction: "",
      user: "",
      hal: "",
      status: "waiting"
    };
  }
  componentDidMount() {
    const socket = io("http://localhost:5000");
    socket.on("connect", () => {
      console.log("Connected to the socket server");
    });

    socket.on("queueData", (data) => {
      console.log("Received data:", data);
      console.log("Received data queue:", data.queue);
      this.setState({ queue: data.queue }, () => {
        console.log(this.state.queue);
      });
      this.setState({ instruction: data.instruction }, () => {
        console.log(this.state.instruction);
      });
      // other attributes, user, hal, status ignored here for simplicity
    });

    this.socket = socket;
  }

  componentWillUnmount() {
    this.socket.disconnect();
  }


  renderData = () => {
    console.log("rendered queue", this.state.queue);
    if (this.state.queue === undefined) {
      return null;
    }
    return this.state.queue.map((task, index) => (
      
        
{task} {index === 0 && this.state.status === "working" && (
)}
)); }; render() { return (
{this.renderData()}
Instruction: {this.state.instruction}
); } } export default App;

Ich möchte, dass die Webseite sofort aktualisiert wird, wenn neue Daten eingehen. Ich habe setState eine Rückruffunktion hinzugefügt, aber sie funktioniert immer noch nicht.

P粉043566314P粉043566314398 Tage vor700

Antworte allen(1)Ich werde antworten

  • P粉617597173

    P粉6175971732023-09-18 11:56:59

    在应用程序中使用socket.io时,由于多种因素,您可能会遇到在接收数据后更新状态时出现延迟的情况。例如socket.io的异步性质、状态管理问题、事件处理、React组件生命周期等等。

    Antwort
    0
  • StornierenAntwort