我在状态同步方面遇到问题。当我单击编辑器的外部(想要关闭它)时,我想将实际文本传递回父节点(回调函数)。
但是,当我在 queryText
外部单击时,状态似乎总是落后一步。 (例如:如果编辑器中有 abc
,我输入 d
,CALLBACK: abc
,我输入 e
,回调:abcd
等等...)。
如果我在编辑器外部单击,如何才能实现 queryText
的实际状态?
import React, {useEffect, useState} from "react";
import AceEditor from "react-ace";
import "ace-builds/src-noconflict/mode-mysql";
import "ace-builds/src-noconflict/theme-eclipse";
import "./SQLEditor.css"
function SQLEditor({queryTab, active, callback}) {
const [queryText, setQueryText] = useState(queryTab[active].content)
//Setting a onClickListener somewhere else
//This function is getting called when I click outside of the Editor
function handleClickOutside() {
document.removeEventListener("mousedown", handleClickOutside);
console.log("CALLBACK:" + queryText) //Problem here
callback(active, {content: queryText})
setInEditor(false)
}
}
//Implementing useEffect for debugging
useEffect(() => {
console.log(queryText); //Here I'm getting the right one.
}
return (
<AceEditor
mode="mysql"
theme="eclipse"
name="blah2"
onChange={(newValue) => {
setQueryText(newValue) //Seting text to new value
console.log(newValue) //Getting the correct updated value
}}
fontSize={16}
/>
</div>
)
}
export default SQLEditor;
最佳答案
添加下面useEffect
,
useEffect(() => {
if(!inEditor){
callback(active, {content: queryText});
console.log(queryText);
}
}, [inEditor, queryText])
并将您的 handleClickOutside
更新为,
function handleClickOutside() {
document.removeEventListener("mousedown", handleClickOutside);
setInEditor(false);
}
关于javascript - react 异步状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67318811/