这是我的代码:
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
套接字事件?