Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

reactjs - React useState with WebSocket causes array to not update correctly

Hello I am attempting to use WebSockets together with react and (electron if it matters)

On open behaves as I would expect. So the message 'Connection opened' gets added to the start of a new array and is displayed correctly. Basically an unshift.

OnMessage however behaves bizarrely. It just overwrites the first element of the array. Even though the same 'addMessage' function is being called.

The console log confirms this with the output being the array.

What could be causing this?

I tried placing the on message assignments into different useEffect hooks like in

this post but it apparently had no effect.


const DebugScreen: FunctionComponent = () => {
    const [messages, setMessages] = useState<Array<string>>([]);
    const socket = useRef<WebSocket>();

    useEffect(() => {
        openConnection();
        return () => {
            if (socket.current) {
                socket.current.close();
            }
        }
    }, []);


    const openConnection = () => {
        socket.current = new WebSocket('wss://localhost');

        if (!socket.current) return;

        socket.current.onopen = () => addMessage('Connection opened');
        socket.current.onmessage = ({ data }) => addMessage(data.toString());
        socket.current.onerror= err => console.log(err);
    }

    const addMessage = (message: string) => {
        setMessages([message, ...messages]);

    };

    const sendWebsocketMessage = () {
        if (!socket.current) return;
        console.log('sendWebsocketMessage: ' + messages);
        socket.current.send(
            JSON.stringify({
                test: 'data'
                },
            })
        );
    }
    const logMessages = () => console.log(messages);

    return (
        <div>
            
            {/* Display server responses */}
            {messages.map((message) => <p key={Math.random().toString()}>{message}</p>)}

            {/* 1) Connect to Cortex Socket */}
            <button onClick={openConnection} >1) Open Cortex Connection</button>

            {/* 2) Sent WebSocket message */}
            <button onClick={sendWebsocketMessage}>Request Cortex Access</button>
            
            <button onClick={logMessages}>Log Messages</button>
        </div>
    );
}

question from:https://stackoverflow.com/questions/65941021/react-usestate-with-websocket-causes-array-to-not-update-correctly

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

1 Reply

0 votes
by (71.8m points)

You should get current messages from previous state:

  const addMessage = (message: string) => {
    setMessages((prevMessages) => [...prevMessages, message]);
  };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...