TypeError: msg.map is not a function
TypeError: msg.map is not a function
我正在尝试使用 React、节点和 mongodb 创建实时在线聊天。在我看来,聊天应该以这种方式工作:客户端将他创建的消息对象发送到服务器以通过 rest(正常工作)和套接字保存它,以便套接字服务器将消息“广播”到服务器中的每个套接字同一个房间(根据本地存储中存储的内容将连接上的插座放在一个房间中)。所以,同一个房间里的其他客户应该会收到这条消息,并将它发生在聊天中。但这不是工作。实际上,会出现以下错误:Uncaught TypeError: msg.map is not a function
这是我的反应代码:
import {useState, useEffect} from 'react';
import axios from 'axios';
import { io } from "socket.io-client";
const Chat = () => {
const [msg, setMsg] = useState([]);
const [message, setMessage] = useState('');
const socket = io("http://localhost:5050");
useEffect(() => {
if(v.group.name){
axios.get(`http://localhost:5050/chat/getmsg/${v.group.name}`)
.then(group => {
setMsg(group.data)
})
}
}, [v.group.name])
useEffect(() => {
if(localStorage.getItem('isG') === '1'){
socket.on("connect", () => {
socket.emit("groupName", {id:localStorage.getItem('gruop')})
})
socket.on("message", messageS => {
if(messageS.sender !== localStorage.getItem('user'))
setMsg(...msg, messageS)
})
}
// eslint-disable-next-line
}, [socket])
const sendMSG = (e) => {
e.preventDefault();
if(message !== ""){
axios.post("http://localhost:5050/chat/sendmsg", {name:v.group.name, sender:localStorage.getItem('user'), text:message})
.then(() => {
setMessage('');
socket.emit("message", {name:v.group.name, sender:localStorage.getItem('user'), text:message})
setMsg(...msg, {name:v.group.name, sender:localStorage.getItem('user'), text:message})
});
}
}
return <div className="containerLogin1">
<div>
<h3>Chat Name</h3>
</div>
<div className="chatSpace">
{
msg.map((m) => {
return <p key={m._id}>{m.text}</p>
})
}
</div>
<form className="sMSG">
<input type="input" style={{'border':'2px solid black'}} value={message} onChange={(e) => setMessage(e.target.value)}/>
<button className="buttSend" onClick={sendMSG} spellCheck="false">Send</button>
</form>
</div>
}
这是服务器代码,但我认为他工作正常:
....
const httpServer = app.listen(port, () => {console.log(`Server listening on port ${port}`)});
const { Server } = require("socket.io");
const io = new Server(httpServer, {
cors : {
origin: "*",
methods:["GET", "POST"]
}
} );
io.on("connection", (socket) => {
let currentRoom = "";
socket.on("groupName", msg => {
socket.join(msg.id + "")
currentRoom = msg.id
})
socket.on("text-change", newText => {
io.to(currentRoom).emit( "text-change", {text:newText, emitter:socket.id})
})
socket.on("message", message => {
io.to(currentRoom).emit("message", message);
})
})
我试了一大堆 console.log 来查看错误可能出在哪里,但我找不到。似乎在代码的某处,msg 从数组变成了对象,因此 map 函数崩溃了。有人可以帮帮我吗?谢谢
您的代码中有这两行,您正在尝试复制最后一个数组并向其添加新对象:
setMsg(...msg, messageS);
并且:
setMsg(...msg, {name:v.group.name, sender:localStorage.getItem('user'), text:message});
这些部分是问题所在,您应该在它们周围添加[]。所以:
setMsg([...msg, messageS]);
setMsg([...msg, {name:v.group.name, sender:localStorage.getItem('user'), text:message}]);
我正在尝试使用 React、节点和 mongodb 创建实时在线聊天。在我看来,聊天应该以这种方式工作:客户端将他创建的消息对象发送到服务器以通过 rest(正常工作)和套接字保存它,以便套接字服务器将消息“广播”到服务器中的每个套接字同一个房间(根据本地存储中存储的内容将连接上的插座放在一个房间中)。所以,同一个房间里的其他客户应该会收到这条消息,并将它发生在聊天中。但这不是工作。实际上,会出现以下错误:Uncaught TypeError: msg.map is not a function
这是我的反应代码:
import {useState, useEffect} from 'react';
import axios from 'axios';
import { io } from "socket.io-client";
const Chat = () => {
const [msg, setMsg] = useState([]);
const [message, setMessage] = useState('');
const socket = io("http://localhost:5050");
useEffect(() => {
if(v.group.name){
axios.get(`http://localhost:5050/chat/getmsg/${v.group.name}`)
.then(group => {
setMsg(group.data)
})
}
}, [v.group.name])
useEffect(() => {
if(localStorage.getItem('isG') === '1'){
socket.on("connect", () => {
socket.emit("groupName", {id:localStorage.getItem('gruop')})
})
socket.on("message", messageS => {
if(messageS.sender !== localStorage.getItem('user'))
setMsg(...msg, messageS)
})
}
// eslint-disable-next-line
}, [socket])
const sendMSG = (e) => {
e.preventDefault();
if(message !== ""){
axios.post("http://localhost:5050/chat/sendmsg", {name:v.group.name, sender:localStorage.getItem('user'), text:message})
.then(() => {
setMessage('');
socket.emit("message", {name:v.group.name, sender:localStorage.getItem('user'), text:message})
setMsg(...msg, {name:v.group.name, sender:localStorage.getItem('user'), text:message})
});
}
}
return <div className="containerLogin1">
<div>
<h3>Chat Name</h3>
</div>
<div className="chatSpace">
{
msg.map((m) => {
return <p key={m._id}>{m.text}</p>
})
}
</div>
<form className="sMSG">
<input type="input" style={{'border':'2px solid black'}} value={message} onChange={(e) => setMessage(e.target.value)}/>
<button className="buttSend" onClick={sendMSG} spellCheck="false">Send</button>
</form>
</div>
}
这是服务器代码,但我认为他工作正常:
....
const httpServer = app.listen(port, () => {console.log(`Server listening on port ${port}`)});
const { Server } = require("socket.io");
const io = new Server(httpServer, {
cors : {
origin: "*",
methods:["GET", "POST"]
}
} );
io.on("connection", (socket) => {
let currentRoom = "";
socket.on("groupName", msg => {
socket.join(msg.id + "")
currentRoom = msg.id
})
socket.on("text-change", newText => {
io.to(currentRoom).emit( "text-change", {text:newText, emitter:socket.id})
})
socket.on("message", message => {
io.to(currentRoom).emit("message", message);
})
})
我试了一大堆 console.log 来查看错误可能出在哪里,但我找不到。似乎在代码的某处,msg 从数组变成了对象,因此 map 函数崩溃了。有人可以帮帮我吗?谢谢
您的代码中有这两行,您正在尝试复制最后一个数组并向其添加新对象:
setMsg(...msg, messageS);
并且:
setMsg(...msg, {name:v.group.name, sender:localStorage.getItem('user'), text:message});
这些部分是问题所在,您应该在它们周围添加[]。所以:
setMsg([...msg, messageS]);
setMsg([...msg, {name:v.group.name, sender:localStorage.getItem('user'), text:message}]);