React Hooks & UseEffect not updating display with socketIO data. Only renders elements in array

女生的网名这么多〃 提交于 2019-12-24 10:44:52

问题


import React, {useState, useEffect} from 'react';
import socketIO from 'socket.io-client';
import Container from 'react-bootstrap/Container';


function Sock() {
   const [textData, setTextData] = useState([]);

   useEffect(() => {
      const socket = socketIO('http://127.0.0.1:5009');
      socket.on('chat message', (text)  =>  {
         setTextData([
            textData.push(text)
         ]);
         console.log(textData);
      });
   },[]);

  return (
      <Container>
         <h1>Socket</h1>
            {textData.map((text) => <li>{text}</li>)}
      </Container>
  ); 
}

export default Sock;

With help I have managed to display something on the UI but it currently only displays the array count and not the object inside the array. I am fairly new to React hooks any help or suggestions would be greatly appreciated.


回答1:


You have to join your data (text) with existing data (textData), try with:

setTextData([...textData, text]);



回答2:


There are few ways to take care of stale closure but for your simple case, you can use the functional update syntax to get the previous text data, and return a new instance of array (do not mutate existing state, using push).

  useEffect(() => {
    const socket = socketIO("http://127.0.0.1:5009");
    socket.on("chat message", text => {
      setTextData(previousTextData => [...previousTextData, text]);
    });
  }, []);

Using the callback approach, you don't need to put textData in the useEffect's dependency array.



来源:https://stackoverflow.com/questions/59376486/react-hooks-useeffect-not-updating-display-with-socketio-data-only-renders-el

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!