我是 React 和 Hooks 的新手。
我创建了一个简单的搜索栏,用户可以在其中输入一些文本。
然而,如果我console.log
之后的状态onChange
,它总是落后一个字符。
例如:
如果我输入“披萨”,console.log
鞋子“披萨”
我的组件
export default function SearchBar({handlerSearchBar}) {
const classes = useStyles();
const [searchBarQuery, setSearchBarQuery] = React.useState([""])
function handleChange(event){
setSearchBarQuery(event.target.value)
// handlerSearchBar(searchBarQuery)
console.log(searchBarQuery)
}
return (
<form className={classes.container} noValidate autoComplete="off">
<TextField
id="standard-full-width"
label="Searchbar"
style={{ marginLeft: 40, marginRight: 40 }}
placeholder="Write your query"
// helperText="The results will appear below!"
fullWidth
margin="normal"
InputLabelProps={{
shrink: true,
}}
onChange={handleChange}
/>
</form>
);
}
经过一番研究(onChange 事件以 1 个字符延迟更新状态 https://stackoverflow.com/questions/35557512/onchange-event-updates-state-with-1-character-delay), 我明白那个setState
是异步的。
所以我尝试了各种解决方案以使其发挥作用:
1)方案一
function handleChange(event) {
let text = event.target.value;
setSearchBarQuery({
text: text
});
console.log(searchBarQuery)
}
但我有同样的问题(最后一个字符没有被捕获)
2)方案二
function handleChange(event) {
let text = event.target.value;
setSearchBarQuery({
text: text
}, ()=>console.log(searchBarQuery));
}
但我得到Warning: State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().
3)解决方案三
async function handleChange(event) {
await setSearchBarQuery({text: event.target.value});
console.log(searchBarQuery)
}
但我有同样的问题(最后一个字符没有被捕获)