【问题标题】:React page not updating on socket message push despite the data being sent尽管发送了数据,但反应页面没有在套接字消息推送上更新
【发布时间】:2020-07-08 12:42:19
【问题描述】:

我的 socket.io 聊天应用程序基本上功能齐全,但是当消息事件被发送到组 id 时,反应页面没有更新。目前我正在使用映射函数来遍历数组中的所有消息...每次发送消息时,它都会保存在数据库中以备将来使用,但这似乎不是问题,因为我删除了它部分和反应组件仍然没有更新。非常感谢任何帮助...下面的代码--

// Import React dependencies.
import React, { Component } from "react";
import io from 'socket.io-client'
import axios from 'axios'
import Message from '../Message/Message'
import uuid from 'react-uuid'
// Import the Slate components and React plugin.

const ENDPOINT = 'http://localhost:5000/'
export const socket = io.connect(ENDPOINT)


export class LiveChat extends Component {
    constructor() {
        super()
        this.state = {
            messages: [],
            message: "",
            id: "",
            username: ""
        }
    }
    changeHandler = (e) => {
        this.setState({
            message: e.target.value
        })
        socket.emit('typing',)
    }

    clickHandler = () => {
        const data = {
            messageId: uuid(),
            username: this.state.username,
            groupId: this.state.id,
            message: this.state.message,
        }
        console.log(data.messageId)
        socket.emit('message', data)
    }
    async componentDidMount() {
        const { id } = this.props.match.params
        console.log(this.state)
        const response = await axios.get('http://localhost:5000/api/users/userInfo', { withCredentials: true })
        const messages = await axios.get(`http://localhost:5000/live/${id}`)
        console.log(messages.data)
        this.setState({
            messages: messages.data,
            username: response.data.user,
            id: id
        })
        console.log(this.state)
        socket.on('typing', data => {
            console.log(data)
        });
        socket.on(`message-${this.state.id}`, data => {
            console.log(data)
            this.state.messages.push(data)
        })
    }
    render() {
        return (
            <div>
                <input placeholder="message" type="text" onChange={e => this.changeHandler(e)} />
                <button onClick={this.clickHandler}>Submit</button>
                {this.state.messages.map((message) => (
                    <Message key={message.messageId} message={message} />
                ))}
            </div>
        )
    }
}

export default LiveChat;

相关API代码:

io.on("connection", (socket) => {
    console.log("New client connected");
    socket.on('new-operations', function (data) {
        groupData[data.groupId] = data.newValue;
        console.log(groupData[data.groupId])
        io.emit(`new-remote-operations-${data.groupId}`, data)
    })
    socket.on('typing-message', function (message) {
        io.emit('typing', "user is typing")
    })
    socket.on('message', function (data) {
        console.log(data)
        Chat.create({
            messageId: data.messageId,
            username: data.username,
            groupId: data.groupId,
            message: data.message
        })
        io.emit(`message-${data.groupId}`, data)
    })
    io.emit("init-value", initValue)
    socket.on("disconnect", () => {
        console.log("Client disconnected");
        clearInterval(interval);
    });
});

【问题讨论】:

    标签: node.js reactjs websocket


    【解决方案1】:

    这个问题是由 setState 是一个异步函数引起的。因为 setState 不会立即更新状态,所以在你的代码中,在你 setState 为 id 之后,你在 socket.on 函数中读取它,在这种情况下,不能保证得到更新的状态。

    socket.on(`message-${this.state.id}`, data => {...
    

    有关详细信息,请参阅下面的此链接。 setState doesn't update the state immediately

    【讨论】:

      猜你喜欢
      • 2015-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-26
      • 2012-03-25
      • 2012-12-13
      • 2020-08-02
      • 2013-03-21
      相关资源
      最近更新 更多