javascript React 钩子 useState 未随 onChange 更新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/55194317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React hooks useState not updating with onChange
提问by Bj?rn Hjorth
UPDATED QUESTION:
更新的问题:
If I type something in the input field before I scroll the expandedprop gets set to true - correct
如果我在滚动之前在输入字段中输入内容,则expanded道具将设置为 true - 正确
If I scroll down - expanded gets set to false - correct
如果我向下滚动 - 展开设置为 false - 正确
If I type something in the input field now expandedis still false- I expect expandedto be set to trueagain.
如果我现在在输入字段中输入expanded内容仍然是false- 我希望再次expanded设置true。
code:
代码:
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>)
}
回答by cEeNiKc
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.
在反应中更新状态不能保证同步调用。因此,当您在更改状态后立即调用 console.log(expanded) 时,它不会返回新状态。您的组件将在重新渲染时收到新状态。
You can also refer to this blog https://medium.com/@wereHamster/beware-react-setstate-is-asynchronous-ce87ef1a9cf3
你也可以参考这个博客 https://medium.com/@wereHamster/beware-react-setstate-is-asynchronous-ce87ef1a9cf3
Another reference:- useState set method not reflecting change immediately
另一个参考:- useState set 方法不会立即反映更改

