[英]useState Hook not working inside event listener
setter function using useState is not working inside an event listener function.使用 useState 的设置器 function 在事件侦听器 function 中不起作用。
Problem Statement: Develop a search suggestion with "Down/Up" key accessibility.问题陈述:开发具有“向下/向上”键可访问性的搜索建议。
Implementation:执行:
<input
style={{ outline: "none" }}
placeholder="Search Here"
className="w-full text-gray-800"
onClick={() => {
setShowSuggestion(true);
document.addEventListener("keydown", escFunction, false);
}}
onChange={(event) => setTitle(event.target.value)}
value={value}
/>
<div
className={
!showSuggestion
? "hidden"
: "flex flex-row border border-gray-300 border-t-0 mx-auto w-3/4 space-x-4"
}
>
<ul className="w-full">
{people.map((person) => (
<li
key={person.id}
className={cursor === person.id ? "bg-red-500" : ""}
>
{person.name}
</li>
))}
</ul>
</div>
function escFunction(event) {
if (event.keyCode === 27) {
document.removeEventListener("keydown", escFunction);
setShowSuggestion(false);
}
if (event.keyCode === 40) {
const nextId = cursor + 1;
setCursor(nextId); //---------------> this line not setting the value
setTitle(people[nextId].name);
}
}
**Issue: ** The keypress event is triggered, but the setter function doesn't work after first click. **问题:** keypress 事件被触发,但是 setter function 在第一次点击后不起作用。
Instead of adding event listener to document you should add it to input keydown event.而不是将事件侦听器添加到文档中,您应该将其添加到输入 keydown 事件。 Also check for the availability of key for people object before accessing its name -
people[nextId].name
.在访问其名称 -
people[nextId].name
之前,还要检查人员 object 的密钥的可用性。 That should solve your problem:那应该可以解决您的问题:
<input
style={{ outline: "none" }}
placeholder="Search Here"
className="w-full text-gray-800"
onClick={() => {
setShowSuggestion(true);
}}
onKeyDown={escFunction}
onChange={(event) => setTitle(event.target.value)}
value={value}
/>
The value(updated value) of cursor
is not available during the execution of escFunction. cursor 的值(更新值)在
cursor
执行期间不可用。 In order to access the value it has to be converted to setCursor(currentId => currentId + 1);
为了访问该值,它必须转换为
setCursor(currentId => currentId + 1);
or或者
setCursor(currentId =>{
// do pre processing
return cursor+1
})
As hinted in comments:正如评论中所暗示的:
Passing a callback allows you to access the current state value.传递回调允许您访问当前的 state 值。 Your code as it is creates a closure around the state value at the time the child was last rendered.
您的代码在最后一次呈现子项时围绕 state 值创建了一个闭包。
cursor from the state inside that closure function is always the initial value, because of the closure function cursor 来自 state 里面的那个闭包 function 总是初始值,因为闭包 ZC1C4145268E17A94D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.