從socket.io接收的資料不會立即在狀態中反映出來
P粉043566314
P粉043566314 2023-09-17 15:04:28
0
1
540

app.js接收到從伺服器發送的資料(在控制台中顯示),setState不會使用新資料刷新網頁。在console.log("Received data queue:", data.queue)的行中,它也傳回undefined。我期望它是一個特定的值,因為在console.log(data)的行中,它在「queue」鍵下有儲存的值。

這是我的程式碼:

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;

我希望網頁在接收到新資料時立即刷新。我已經在setState中加入了回調函數,但仍然無效。

P粉043566314
P粉043566314

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!