从回调函数中访问使用 useState 定义的状态变量

Access state variables defined with useState from callback function

我的 React 应用程序中有一个评论部分,我想在其他用户发表评论时实时更新它。我使用 socket.io 来监听服务器发送的新评论事件。当应用收到有关新评论的通知时,我会使用新评论数据更新现有 comments 列表。

但是,当我尝试从回调中访问 comments 状态变量时,它始终为空。如何从回调中访问 comments 以便我可以将新数据附加到现有的评论列表中。非常感谢任何帮助。

const Discussion = ({ lessonId,lessonName }) => {
    const [comments, setComments] = useState([]);

    const updateComments = (data) => {
      // this is always empty, even though it contains a list of objects and rendered as comments
      console.log(comments) 
      // This results in something like [data]. Existing objects have been disappeared.
      setComments([...comments,data])
    }

    useEffect(() => {
      Axios.get('/courses/lessons/' + lessonId + '/comments')
        .then(res => {
           console.log(res.data);
           setComments(res.data);

           socket.on('reply',data => {
             console.log(data)
           })
           // existing list of comments is updated with new data.
           socket.on('comment_'+lessonId,(data) => updateComments(data))
           })
        .catch(err => {
            console.log(err);
            alert('An error occured');
        });
    }, [lessonId]);

    return <div></div>
};

updateCommentsuseEffect 内部被调用,它使用的注释值将被限制在 useEffect 的闭包中,因此它将无法访问更新的注释值,除非 useEffect依赖于 comments

此处优化的解决方案是使用功能状态更新器

const updateComments = (data) => {
  setComments(prevComments => [...prevComments,data])
}