简体   繁体   English

在 useEffect 将 onChange 事件设置为元素后,如何获取更新状态?

[英]How do I get updated state after useEffect has set an onChange event to an element?

I have an input field that needs an onChange event to be bound on mounting the component.我有一个需要在安装组件时绑定 onChange 事件的输入字段。 The onChange event needs to update the state. onChange 事件需要更新状态。 However, the state never gets updated because the onChange event always has the initial state.但是,状态永远不会更新,因为 onChange 事件始终具有初始状态。 What is the best way to make this work?使这项工作的最佳方法是什么?

Here is my code:这是我的代码:

const someComponent: FC<someComponent> = props => {
    const [count, setCount] = useState(0);
    const someFunction = () => {
        console.log(count) // 0
        setCount(count+ 1);
        console.log(count) // Also 0
    }

    useEffect(() => {
        inputField.onChange = () => {
          someFunction();
        }
    }, [])
}

You can tweek your useEffect to get the updated state.您可以调整 useEffect 以获取更新的状态。 State setting is async in nature.状态设置本质上是异步的。 - ——

const someComponent: FC<someComponent> = props => {
    const [count, setCount] = useState(0);
    const someFunction = () => {
        console.log(count) // 0
        setCount(count+ 1);
        console.log(count) // Also 0
    }

  useEffect(() => {
        inputField.onChange = () => {
          someFunction();
        }
    }, [])

    useEffect(() => {
        console.log(count) //updated value//
    }, [count]) // adding count to dependency array will cause this  useEffect to run on every count change //
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM