Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. Even with arrow functions used
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. Even with arrow functions used
所以我正在使用 react 、 redux 、 node 、 express 和 socket.io 创建一个实时聊天应用程序我的代码在没有 addMessage 操作的情况下工作,即使我将它更改为 [...messages ,message] 并使用 useState 定义消息,它仍然显示错误。
这是我在客户端发生错误的代码。
import Header from "./Header";
import MessageBox from "./MessageBox";
import MessageBody from "./MessageBody";
import {addMessage} from "../actions"
import { useEffect,useState } from "react";
import { connect } from "react-redux";
import io from 'socket.io-client';
let socket;
const Chat = ({name,addMessage}) => {
const [message,setMessage] = useState('');
const ENDPOINT = 'localhost:5000';
useEffect(()=>{
socket =io(ENDPOINT);
socket.emit('join',{name},()=>{
})
return ()=>{
socket.disconnect();
socket.off();
}
},[name]);
useEffect(()=>{
socket.on('message',(message)=>{
addMessage(message)
console.log(message);
});
return ()=>{
socket.off();
}
});
const sendMessage = (event)=>{
event.preventDefault();
if(message){
socket.emit('sendMessage',message,()=>setMessage(''))
}
}
return (
<div style={{backgroundColor:"#414a4c"}}>
<Header/>
<MessageBody name={name}/>
<MessageBox message={message} setMessage={setMessage} sendMessage={sendMessage}/>
</div>
)
}
const mapStateToProps =(state)=>{
return{
name : state.enteredName
}
}
export default connect(mapStateToProps,{addMessage})(Chat)
这是消息框组件
const MessageBox = ({message,setMessage,sendMessage}) => {
return (
<section className="bg-dark text-light p-1" style={style}>
<div className="container">
<div className="d-flex justify-content-around align-items-center">
<div className="input-group news-input">
<input type="text" className="form-control"
value={message}
onChange={({ target: { value } }) => setMessage(value)}
placeholder="Write Your Messages Here"
onKeyPress={(e)=>e.key==='Enter'&& sendMessage(e) }
/>
</div>
<i className="bi bi-telegram ps-2 pb-1" style={{fontSize:"40px"}}
onClick={(e)=> sendMessage(e)}
>
</i>
</div>
</div>
</section>
)
}
const style = {
position : "fixed",
bottom: "0px",
width:"100%"
}
export default MessageBox
这是服务器端代码
const express = require('express');
const socketio = require('socket.io');
const http = require('http');
const {addUser,removeUser,getUser,getAllUsers} = require('./users');
corsOptions={
cors: true,
origins:["http://localhost:3000"],
}
const PORT = process.env.PORT || 5000;
const router = require('./router');
const app = express();
const server = http.createServer(app);
const io = socketio(server, corsOptions);
io.on('connection',(socket)=>{
socket.on('join',({name},callback)=>{
const {error,user} = addUser({id:socket.id,name});
if(error)return callback(error);
socket.emit('message',{user:'admin',text:`${user.name} welcome to the chat.`});
socket.broadcast.emit('message',{user:'admin',text:`${user.name} has joined the chat`})
socket.join(user);
callback();
})
socket.on('sendMessage',(message)=>{
const user = getUser(socket.id);
io.emit('message',{user:user.name,text:message});
});
socket.on('disconnect',()=>{
console.log("user just left");
socket.broadcast.emit('message',{user:'admin',text:`${user.name} has left the chat`})
})
})
app.use(router);
server.listen(PORT,()=>console.log(`The server is running on ${PORT}`));
你必须指定
useEffect(()=>{
socket.on('message',(message)=>{
addMessage(message)
console.log(message);
});
return ()=>{
socket.off();
}
}, [] <- dependency array);
主要问题出在聊天框组件中,我在其中使用了 useState 并导致重新呈现,删除代码后现在可以正常工作。
所以我正在使用 react 、 redux 、 node 、 express 和 socket.io 创建一个实时聊天应用程序我的代码在没有 addMessage 操作的情况下工作,即使我将它更改为 [...messages ,message] 并使用 useState 定义消息,它仍然显示错误。
这是我在客户端发生错误的代码。
import Header from "./Header";
import MessageBox from "./MessageBox";
import MessageBody from "./MessageBody";
import {addMessage} from "../actions"
import { useEffect,useState } from "react";
import { connect } from "react-redux";
import io from 'socket.io-client';
let socket;
const Chat = ({name,addMessage}) => {
const [message,setMessage] = useState('');
const ENDPOINT = 'localhost:5000';
useEffect(()=>{
socket =io(ENDPOINT);
socket.emit('join',{name},()=>{
})
return ()=>{
socket.disconnect();
socket.off();
}
},[name]);
useEffect(()=>{
socket.on('message',(message)=>{
addMessage(message)
console.log(message);
});
return ()=>{
socket.off();
}
});
const sendMessage = (event)=>{
event.preventDefault();
if(message){
socket.emit('sendMessage',message,()=>setMessage(''))
}
}
return (
<div style={{backgroundColor:"#414a4c"}}>
<Header/>
<MessageBody name={name}/>
<MessageBox message={message} setMessage={setMessage} sendMessage={sendMessage}/>
</div>
)
}
const mapStateToProps =(state)=>{
return{
name : state.enteredName
}
}
export default connect(mapStateToProps,{addMessage})(Chat)
这是消息框组件
const MessageBox = ({message,setMessage,sendMessage}) => {
return (
<section className="bg-dark text-light p-1" style={style}>
<div className="container">
<div className="d-flex justify-content-around align-items-center">
<div className="input-group news-input">
<input type="text" className="form-control"
value={message}
onChange={({ target: { value } }) => setMessage(value)}
placeholder="Write Your Messages Here"
onKeyPress={(e)=>e.key==='Enter'&& sendMessage(e) }
/>
</div>
<i className="bi bi-telegram ps-2 pb-1" style={{fontSize:"40px"}}
onClick={(e)=> sendMessage(e)}
>
</i>
</div>
</div>
</section>
)
}
const style = {
position : "fixed",
bottom: "0px",
width:"100%"
}
export default MessageBox
这是服务器端代码
const express = require('express');
const socketio = require('socket.io');
const http = require('http');
const {addUser,removeUser,getUser,getAllUsers} = require('./users');
corsOptions={
cors: true,
origins:["http://localhost:3000"],
}
const PORT = process.env.PORT || 5000;
const router = require('./router');
const app = express();
const server = http.createServer(app);
const io = socketio(server, corsOptions);
io.on('connection',(socket)=>{
socket.on('join',({name},callback)=>{
const {error,user} = addUser({id:socket.id,name});
if(error)return callback(error);
socket.emit('message',{user:'admin',text:`${user.name} welcome to the chat.`});
socket.broadcast.emit('message',{user:'admin',text:`${user.name} has joined the chat`})
socket.join(user);
callback();
})
socket.on('sendMessage',(message)=>{
const user = getUser(socket.id);
io.emit('message',{user:user.name,text:message});
});
socket.on('disconnect',()=>{
console.log("user just left");
socket.broadcast.emit('message',{user:'admin',text:`${user.name} has left the chat`})
})
})
app.use(router);
server.listen(PORT,()=>console.log(`The server is running on ${PORT}`));
你必须指定
useEffect(()=>{
socket.on('message',(message)=>{
addMessage(message)
console.log(message);
});
return ()=>{
socket.off();
}
}, [] <- dependency array);
主要问题出在聊天框组件中,我在其中使用了 useState 并导致重新呈现,删除代码后现在可以正常工作。