import React, { useEffect, useState } from 'react';
import MonacoEditor from '@/components/Edit/Index';
import { EditorInstance } from '@/components/Edit/types';
import EventNotify from '@/utils/EventNotify';
import io from 'socket.io-client';
export interface TermProps {
msg: string;
}
export default function Index(props: TermProps) {
const { msg } = props;
const [text, setText] = useState('');
const [edit, setEdit] = useState<EditorInstance>();
const editorDidMount = (editInstance: EditorInstance) => {
setEdit(editInstance);
};
useEffect(() => {
//创建websock连接,并监听
const socket = io.connect('http://127.0.0.1:7001/webide', {
transports: ['websocket'],
});
socket.on('msg', (data: any) => {
EventNotify.emit(EventNotify.EVENT_CODE_VIEW, data);
});
//监听组件共享事件
EventNotify.on(EventNotify.EVENT_CODE_VIEW,(data:any)=>{
//问题:这里虽然是在自定义事件的回调里,但是text似乎始终是最初的空字符串
console.log(text);
const newText = text + data.text;
setText(newText);
})
}, []);
//创建socket和监听共享事件在useEffect中进行,模拟componentDidMount
return (
<div>
<MonacoEditor
editorDidMount={editorDidMount}
height={document.body.clientHeight + 'px'}
language={'logLanguage'}
theme={'logTheme'}
value={text}
/>
</div>
);
}
代码如上,想创建socket和监听共享事件在useEffect中进行,模拟componentDidMount时机,但是发现自定事件回调中拿到的state始终为初始值。如果将text写在useEffect中可以拿到最新的值,但是会循环绑定。 求助大神帮忙看下该怎么处理。
setText(oldText => oldText + data.text)