在套接字事件上更新状态数组中的数据

update data in state array on socket event

这是我的代码:

import React, { useEffect, useState } from 'react';

import Loader from './Loader.jsx';
import Unit from './Unit.jsx';
import Comments from './Comments.jsx';

export default function App() {

  const [unit, setUnit] = useState(null);
  const [comments, setComments] = useState([]);


  useEffect(() => {
    // subscribing to unit's updates
    io.socket.get(`/unit/${window.unitid}/subscribe`, (resData) => {
      setUnit(resData.unit);
      setComments(resData.comments);
    });

    // 'unit' event is fired when a comment is added to the unit
    io.socket.on('unit', (event) => {
      if (event.verb === 'addedTo') {
        console.log('NEW COMMENT ADDED');
        const c = comments; // <-- comments is empty
        c.push(event.added);
        setComments(c);
      }
    });
  }, []);  

  if (!unit) {
    return <Loader />;
  }

  return (
    <>
      <Unit unit={unit} />
      <Comments comments={comments} />
    </>
  )
}

我想把新添加的评论推送到comments但是数组是空的。但是,<Comments /> 已正确填充注释。 如何在套接字事件上更新 comments

答案已在 Reddit 上给出。使用功能更新。

io.socket.on('unit', (event) => {
  if (event.verb === 'addedTo') {
    console.log('NEW COMMENT ADDED');
    setComments( prev => [...prev, event.added])
  }
});