我正在使用 React 和 Socket.io,但我有一个问题。我在输入字段中写入的每个字符都会创建一个新的套接字 ID,我不希望这种情况发生。当我在 onChange 方法中删除 setUsername(e.target.value) 时,没有创建套接字。这是我的代码:
服务器端:
const express = require('express'),
app = express(),
http = require('http').createServer(app),
PORT = 5000,
io = require('socket.io')(http);
io.on('connection', (socket) => {
console.log('New client with id: ' + socket.id);
socket.on('disconnect', () => console.log('Disconnected'));
});
http.listen(PORT, (req, res) => console.log('Server has started on port: ' + PORT));
客户端:
import React, { useEffect, useState } from 'react';
import './App.css';
import io from 'socket.io-client';
import 'materialize-css/dist/css/materialize.min.css';
import M from "materialize-css";
function App() {
const socket = io.connect('http://localhost:5000');
const [username, setUsername] = useState('');
useEffect(() => {
M.AutoInit();
//eslint-disable-next-line
}, []);
const handleSubmit = e => {
e.preventDefault();
};
const onChange = e => {
setUsername(e.target.value);
}
return (
<div>
<form onClick={e => handleSubmit(e)}>
<input id="name" placeholder="Username..." onChange={e => onChange(e)} required />
<button type="submit">Submit</button>
</form>
</div>
);
}
export default App;
先感谢您