gpt4 book ai didi

javascript - react 异步状态

转载 作者:行者123 更新时间:2023-12-04 07:43:34 26 4
gpt4 key购买 nike

我有状态同步问题。当我点击编辑器的外部(想关闭它)时,我想将实际文本传递回父节点( callback 函数)。
但是当我在 queryText 之外点击时状态似乎总是落后一步。 (例如:如果编辑器中有 abc,我输入 dCALLBACK: abc ,我输入 eCALLBACK: 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com