Apabilaapp.js
接收到从服务器发送的数据(在控制台中显示),setState
不会使用新数据刷新网页。在console.log("Received data queue:", data.queue)
的行中,它也返回undefined
。我期望它是一个特定的值,因为在console.log(data)
berada dalam satu baris, ia mempunyai nilai yang disimpan di bawah kekunci "baris gilir".
Ini kod saya:
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) => ()); }; render() { return ( {task} {index === 0 && this.state.status === "working" && ( )}); } } export default App;{this.renderData()} Instruction: {this.state.instruction}
Saya mahu halaman web dimuat semula dengan segera apabila data baharu diterima. Saya telah menambah fungsi panggil balik untuk setState, tetapi ia masih tidak berfungsi.
Apabila menggunakan socket.io dalam aplikasi anda, anda mungkin mengalami kelewatan dalam mengemas kini status selepas menerima data disebabkan beberapa faktor. Contohnya, sifat tak segerak socket.io, isu pengurusan keadaan, pengendalian acara, kitaran hayat komponen React, dsb.