Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

reactjs - Socket.io Node.js and React - function multiple execution

I'm trying to send message using Socket.io. When I open chat and send messages it works correctly. The problem is when I change the page/route, then comeback to chat(rerender), send message and recieve data from socket my socket function socket.on executes multiple times(how many times have I rerendered). I tried different variants, but didn't solve. Thanks!

The client code

const ENDPOINT = 'http://localhost:8080'

let socket
let ChatPage = (props) => {
    let test = useSelector(getMessages)
    const [messages, setMessages] = useState(props.messages)
    useEffect(() => {
            socket = io(ENDPOINT)
    }, [])
    useEffect(() => {
        setMessages(props.messages)
    }, [props.messages])
    useEffect(() => {

        socket.on('incMsg', (msg) => {
            props.setRealMessage(msg)
            setMessages((prevMessages) => {
                return [...prevMessages, msg]
            })
        })
    }, [])
    let sendMessage = (msg) => {
        props.setRealMessage(msg)

        socket.emit('msg', msg)
    }
    debugger
    return (
        <div style={{ display: 'flex', width: '-webkit-fill-available' }}>

            <NavPanel />
            <Messenger sendMessage={sendMessage} />
        </div>
    );
}
const mapStateToProps = (state) => {
    return {
        messages: state.messenger.messages
    }
}

export default compose(
    connect(mapStateToProps, { setRealMessage }),
    withRouter
)(ChatPage);

The server code

const http = require('http').Server(app)
const socketio = require('socket.io')
const io = socketio(http)
io.listen(8080); 
io.on('connection', (socket) => {
    socket.on('msg', (msg)=>{
        console.log(msg);
        socket.broadcast.emit('incMsg', msg)
    })
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...