0

这是我的代码:

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套接字事件?

4

1 回答 1

0

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

io.socket.on('unit', (event) => {
  if (event.verb === 'addedTo') {
    console.log('NEW COMMENT ADDED');
    setComments( prev => [...prev, event.added])
  }
});
于 2020-12-09T08:10:16.223 回答