简体   繁体   English

如何防止使用功能组件重新渲染并反应钩子?

[英]How to prevent a re-render with a functional component and react hooks?

Issue : Web Application re-rendering with input onChange event, thus causing socket to disconnect then reconnect.问题:Web 应用程序使用输入 onChange 事件重新渲染,从而导致套接字断开连接然后重新连接。

Detail : I am creating a small multiplayer game with Socket.io, React, Express, PostgreSql, and Nodejs.详细信息:我正在使用 Socket.io、React、Express、PostgreSql 和 Nodejs 创建一个小型多人游戏。 I would like the user to be able to search for a room name with an input box and a submit button or create a game with a button.我希望用户能够使用输入框和提交按钮搜索房间名称,或者使用按钮创建游戏。

Question : Is there a way to prevent a re-render when the user inputs the room code in the input box?问题:当用户在输入框中输入房间代码时,有没有办法防止重新渲染?


Code :代码

App.js应用程序.js

const App = () => {
    const socket = io();
    const [roomCode, setRoomCode] = useState('');

        // CREATE ROOM CODE
    const createRoom = () => {
        socket.emit('create', true)
        socket.once('roomCreated', room => {
            axios.post(`/room/roomCode?room=${room}`)
                .then(({ data }) => {
                    console.log(data);
                })
                .catch(err => console.warn(err))
        })
    }

        // JOIN SPECIFIC ROOM
    const joinRoom = () => {
        axios.post(`/room/findRoom?roomCode=${roomCode}`)
            .then(({ response }) => {
                console.info(response)
            })
            .catch(err => console.warn(err))
    }

    return (
        <div>
            <button
                onClick={createRoom}
            >
                Create
            </button>
            <input
                placeholder="Room Code"
                onChange={(e) => { setRoomCode(e.target.value) }}
            />
            <button onClick={joinRoom}>
                Enter Room Code
            </button>
        </div>
    )
}

Room.js route Room.js 路由

roomRouter.post('/findRoom', (req, res) => {
    const { roomCode } = req.query
    Room.findOne({
        where: {
            room_code: roomCode,
        }
    })
        .then(room => {
            room ? res.send(room) : res.send('room does not exist')
        })
        .catch(err => console.warn(err))
})

Each time state changes, the entire component is re-rendered, including your first line const socket = io() .每次 state 更改时,都会重新渲染整个组件,包括您的第一行const socket = io() Try moving that line on top of your component like so:尝试将那条线移动到组件顶部,如下所示:

const socket = io()

const App = () => {
  // ...
}

changing your socket declaration to将您的套接字声明更改为

 const [socket] = useState(io());

should fix the issue.应该解决这个问题。

Or simple move it outside the component或者简单地将它移到组件之外

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM