React Hooks &UseEffect 不使用 socketIO 数据更新显示.只渲染数组中的元素 [英] React Hooks & UseEffect not updating display with socketIO data. Only renders elements in array

查看:25
本文介绍了React Hooks &UseEffect 不使用 socketIO 数据更新显示.只渲染数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;

在帮助下,我设法在 UI 上显示了一些东西,但它目前只显示数组计数而不是数组内的对象.我对 React 钩子相当陌生,任何帮助或建议将不胜感激.

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.

推荐答案

您必须将您的 data (text) 与现有的 data (textData) 连接起来,请尝试:

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

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

这篇关于React Hooks &amp;UseEffect 不使用 socketIO 数据更新显示.只渲染数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆