javascript - react 异步状态

标签 javascript reactjs react-hooks state

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

相关文章:

javascript - react : How to wait until ref is available when inserted (rendered) within a second container

javascript - 带有反应钩子(Hook)的多个计数器

reactjs - 如何正确地将相同的 Prop 传递给多个组件?

javascript - 打包时如何让webpack不使用window对象?

javascript - 使用 useState Hook 在功能组件中使用 Children 来 React Render prop

javascript - jQuery 列表项删除

reactjs - 使用 babel-jest 来开 Jest 但仍然出现语法错误

javascript - 面板透明度 firefox 插件

javascript - 此 javascript 函数和显示命令示例的更高效版本

javascript - 获取特定剑道网格列中的所有值