React 钩子 useState 未随 onChange 更新 [英] React hooks useState not updating with onChange

查看:34
本文介绍了React 钩子 useState 未随 onChange 更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新的问题:

如果我在滚动之前在输入字段中输入内容,expanded 属性将设置为 true - 正确

If I type something in the input field before I scroll the expanded prop gets set to true - correct

如果我向下滚动 - 展开设置为 false - 正确

If I scroll down - expanded gets set to false - correct

如果我现在在输入字段中输入内容 expanded 仍然是 false - 我希望 expanded 被设置为 true 再次.

If I type something in the input field now expanded is still false - I expect expanded to be set to true again.

代码:

export default () => {

const [expanded, setExpanded] = useState(true)

let searchInput = React.createRef()
let scrollTopValue = 0;

function handleSearchInput() {
    console.log(Boolean(searchInput.current.value.length))
    setExpanded(Boolean(searchInput.current.value.length)) // first time true, don't get re triggered

}

useEffect(() => {
    window.addEventListener('scroll', handleScroll)
    return () => window.removeEventListener('scroll', handleScroll)
}, []);

function handleScroll() {
    setExpanded(scrollTopValue > document.documentElement.scrollTop)
    scrollTopValue =  document.documentElement.scrollTop
}

return (
<header>
   {expanded? 'expanded': 'nope'}
    <input role="search" ref={searchInput} onChange={handleSearchInput}></input>

</header>)
}

推荐答案

在 react 中更新状态不保证同步调用.因此,当您在更改状态后立即调用 console.log(expanded) 时,它不会返回新状态.您的组件将在重新渲染时获得新状态.

Updating state in react is not guaranteed synchronous call. So, when you are calling console.log(expanded) just after changing state it won't return the new state. Your component will receive new state on the re-render.

你也可以参考这个博客https://medium.com/@wereHamster/beware-react-setstate-is-asynchronous-ce87ef1a9cf3

另一个参考:-useState 设置方法不会立即反映更改

这篇关于React 钩子 useState 未随 onChange 更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆