如何在反应中循环更新数组

How to loop through an updating array in react

我正在尝试使用 React.js 练习 socket.io,因此我尝试在两个客户端之间发送消息,但是我在显示消息方面遇到了困难。我想显示过去发送的消息。现在我正在考虑将它作为一个数组来做,因为状态不起作用。当控制台记录数组时,它会显示在控制台中但永远不会呈现出来

import { useEffect, useState } from "react";
import io from "socket.io-client";
import "./App.css";

let socket;
const CONNECTION_PORT = "localhost:3001/";

function App() {
  const [loggedIn, setLoggedIn] = useState(false);
  const [room, setRoom] = useState("");
  const [userName, setUserName] = useState("");
  const [message, setMessage] = useState("");
  var itemArray = [];

  useEffect(() => {
    //connect to the socket
    socket = io(CONNECTION_PORT);

    socket.on("receive-message", (data) => {
      itemArray.push(data);
      console.log("Pong");
      console.log(itemArray);
    });

    //receiving messages
    socket.on("authentication", (bool) => {
      if (bool === true) {
        setLoggedIn(true);
      }
    });
  }, [CONNECTION_PORT]);

  //Sending a request to join the room
  const connectToRoom = () => {
    socket.emit("join-room", room, userName);
  };

  const sendMessage = () => {
    socket.emit("send-message", message);
  };

  return (
    <div className="App">
      {!loggedIn ? (
        <div className="login">
          <input
            type="text"
            placeholder="Name..."
            onChange={(e) => {
              setUserName(e.target.value);
            }}
          />
          <input
            type="text"
            placeholder="Room..."
            onChange={(e) => {
              setRoom(e.target.value);
            }}
          />
          <button onClick={connectToRoom}> Enter Chat</button>
        </div>
      ) : (
        <div>
          <input
            type="text"
            placeholder="Send Message..."
            onChange={(e) => {
              setMessage(e.target.value);
            }}
          />
          <button onClick={sendMessage}>Send Message</button>
          <div>
            {itemArray.map((data) => {
              console.log(data);
            })}
          </div>
        </div>
      )}
    </div>
  );
}
export default App;

您需要 return 数据才能看到 映射 returns 你遍历的每个值,你必须确保说你想在列表中看到数据 请确保return这样

内部地图功能

{itemArray.map((data) => {
              return<li>{data.propertyName}</li>
            })}

这里属性将是对象的任何东西属性

数组正在更新,但是没有什么可以告诉 React 渲染更新。任何这些更改都会导致组件再次呈现:

  1. 道具更新
  2. 状态更新
  3. Context 值变化

React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.

您正在更新组件内的数组变量,但这不会触发渲染。将数组移动到状态:

const [messages, setMessages] = useState([]);
...
useEffect(() => {
    ...
    socket.on("receive-message", (data) => {
      // update the state which triggers a render
      setMessages(prevState => [...prevState, data]);
    });

}, [CONNECTION_PORT]);