简体   繁体   English

useState Hook 在事件侦听器中不起作用

[英]useState Hook not working inside event listener

setter function using useState is not working inside an event listener function.使用 useState 的设置器 function 在事件侦听器 function 中不起作用。

  • visit sandbox: https://codesandbox.io/s/mystifying-austin-e9zgh访问沙箱: https://codesandbox.io/s/mystifying-austin-e9zgh
  • click on search box, a suggestion dropdown will appear点击搜索框,将出现一个建议下拉菜单
  • press down key, it will highlight the next item按向下键,它将突出显示下一项
  • pressing down key again doesn't works [issue], expected behavior: down key should point to next item再次按下向下键不起作用 [问题],预期行为:向下键应指向下一项

Problem Statement: Develop a search suggestion with "Down/Up" key accessibility.问题陈述:开发具有“向下/向上”键可访问性的搜索建议。

Implementation:执行:

  • create a search bar component.创建一个搜索栏组件。
              <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}
                />
  • create a suggestion component.创建一个建议组件。
              <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>
  • on clicking searchbar add event lister to check key press单击搜索栏添加事件列表以检查按键
  • on keyevent == "down arrow key", set selected recommendation = next item in list.在keyevent ==“向下箭头键”上,设置选定的推荐=列表中的下一项。

  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.

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