如何解决使用useState时收到警告
我正在尝试使用套接字在React中创建一个聊天应用程序。我要在给定的代码中尝试实现的一种方法是,确保在聊天容器中聊天的每个用户都由唯一的颜色表示。但即时通讯无法达到预期的效果。我是React的新手。
import React,{ useState,useEffect } from 'react';
import { Input } from 'antd';
import { v4 as uuidv4 } from 'uuid';
function Chat({ socket }) {
const [state,setState] = useState({ message: '',name: 'userName' });
const [messageList,setMsgList] = useState([]);
var userList = [{name: 'You',color: 'green'}];
const handleMessageChange = (e) => {
setState({ ...state,[e.target.name]: e.target.value });
};
useEffect(() => {
//recieving data from socket
socket.on('RCV_MSG',(data) => {
var msgColorIndex;
var msgColor;
if (userList.some((e) => e.name == data.userName)) {
msgColorIndex = userList.map((o) => o.name).indexOf(data.userName);
msgColor = userList[msgColorIndex].color;
const newList = messageList.concat({
id: uuidv4(),source: data.userName + ': ',msg: data.content,color: msgColor,});
setMsgList(newList);
} else {
const newUserList = userList.concat({
name: data.userName,color: '#' + Math.floor(Math.random() * 16777215).toString(16),});
console.log(newUserList);
userList=newUserList;
console.log('user list should be updated');
console.log(userList);
msgColorIndex = userList.map((o) => o.name).indexOf(data.userName);
msgColor = userList[msgColorIndex].color;
const newMsgList = messageList.concat({
id: uuidv4(),source: data.userName,});
setMsgList(newMsgList);
}
});
},[socket,messageList,userList]);
// sending msg to socket
const onMessageSubmit = (e) => {
e.preventDefault();
const { name,message } = state;
const newList = messageList.concat({
id: uuidv4(),source: 'You',msg: message,color: 'green',});
setMsgList(newList);
console.log(message);
console.log(socket);
socket.emit('SEND_MSG',{ content: message },(data) => {
console.log(data);
});
setState({ message: '',name });
};
return (
<div className='chat-body'>
<div className='chat-header'>CHAT</div>
<div className='chat-container' id='chat-container'>
<ul>
{messageList.map((item) => (
<li key={item.id}>
<div className='chat-row'>
<div style={{ color: item.color }}>{item.source}</div>
<div className='chat-spacing'>:</div>
{item.msg}
</div>
</li>
))}
</ul>
</div>
<form onSubmit={onMessageSubmit}>
<div className='chat-input'>
<Input
name='message'
value={state.message}
onChange={handleMessageChange}
placeholder='Type here'
></Input>
<button>Send</button>
</div>
</form>
</div>
);
}
export default Chat;
msgList是一个数组,其元素呈现在聊天容器中,而userList是一个跟踪所有相关用户的数组。
解决方法
我可以提供一些想法
let arrayColor = [ ]
const buildColor = () => {
let newColor = Math.floor(Math.random() * 16777215).toString(16);
if(!arrayColor.includes(newColor)&&newColor.length===6){
arrayColor.push(newColor)
return newColor
}
else{
return buildColor()
}
}
在使用中影响第1行
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。