为什么useState值在useHotkeys回调中未更新?

克里斯

我已经有了react-hotkeys-hooks用于管理按键的React挂钩的以下搜索建议

为什么不selectedUserItemEnter键更新上下键更改时,它保持为0。

import { useHotkeys } from "react-hotkeys-hook";
import React, { useState } from "react";

import "./styles.css";
const itemsByName = [
  {
    id: 1,
    name: "Ice Cream"
  },
  {
    id: 2,
    name: "Banana Pudding"
  },
  {
    id: 3,
    name: "Chocolate Cake"
  },
  {
    id: 4,
    name: "Sponge Cake"
  },
  {
    id: 5,
    name: "Carrot Cake"
  }
];

const App = () => {
  const [selectedUserItem, setSelectedUserItem] = useState(0);

  // const [create] = useMutation(SAVE_USER_ITEM, {
  //   refetchQueries: ["UserItemsQuery"]
  // })

  const itemSelect = (e, item) => {
    e.preventDefault();
    // create({ variables: { input: { id: item.id } } });
    // console.log(item)
  };

  const increment = selectedUserItem => {
    const max = itemsByName.length - 1;
    return max > selectedUserItem ? selectedUserItem + 1 : max;
  };

  const decrement = selectedUserItem => {
    const min = 0;
    return min < selectedUserItem ? selectedUserItem - 1 : min;
  };

  useHotkeys(
    "*",
    (event, handler) => {
      // console.log(handler)
      switch (event.key) {
        case "ArrowDown":
          setSelectedUserItem(selectedUserItem => increment(selectedUserItem));
          break;
        case "ArrowUp":
          setSelectedUserItem(selectedUserItem => decrement(selectedUserItem));
          break;
        case "Enter":
          console.log(selectedUserItem);
          const userItem = itemsByName[selectedUserItem];
          console.log(userItem);
          break;
        default:
          console.log(event.key);
          break;
      }
    },
    {
      filter: () => true
    }
  );

  return (
    <div className="absolute w-3/4 mt-16 ml-8 py-2 bg-white shadow-xl rounded-lg">
      <h1>Index: {selectedUserItem}</h1>
      {itemsByName.map((item, i) => {
        return (
          <div
            href="#"
            onClick={e => itemSelect(e, item)}
            className={`${selectedUserItem === i ? "hovered" : ""} dessert`}
            key={item.id}
          >
            {item.id}: {item.name}
          </div>
        );
      })}
    </div>
  );
};

export default App;
埃米尔·伯杰龙(Emile Bergeron)

useHotkeys内部人员使用useCallbackanduseEffect钩子,需要知道其某些依赖项何时更改。为确保它与这些钩子配合使用,建议像上面提到的其他钩子一样useHotkeys,将deps数组作为最后一个参数传递

deps: any[] = []:依赖数组被附加到回调的备注中。在这里,您定义了回调的内部依赖性。例如,如果回调操作依赖于参照不稳定值或随时间变化的值,则应将此值添加到deps数组中。由于大多数情况下您的回调将不会依赖于任何不稳定的回调或随时间变化的值,因此您可以保留此值,因为默认情况下会将其设置为空数组。

在您的代码中,它看起来像这样:

// These never changes and do not rely on the component scope, so they
// can be defined safely outside the component.
const increment = selectedUserItem => {
  const max = itemsByName.length - 1;
  return max > selectedUserItem ? selectedUserItem + 1 : max;
};

const decrement = selectedUserItem => {
  const min = 0;
  return min < selectedUserItem ? selectedUserItem - 1 : min;
};

const App = () => {
  const [selectedUserItem, setSelectedUserItem] = useState(0);

  useHotkeys(
    "*",
    (event, handler) => {
      switch (event.key) {
        case "ArrowDown":
          setSelectedUserItem(increment);
          break;
        case "ArrowUp":
          setSelectedUserItem(decrement);
          break;
        case "Enter":
          console.log(selectedUserItem, itemsByName[selectedUserItem]);
          break;
        default:
          console.log(event.key);
          break;
      }
    },
    {
      filter: () => true
    },
    // The dependencies array which ensure that the data is up to date in the callback.
    [selectedUserItem, setSelectedUserItem]
  );

  // rest of the component

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

反应useState值未在ref回调中更新

为什么反应功能组件中的回调没有读取更新的状态值

为什么更改值时未更新react挂钩的useState

反应:事件回调中的属性值未更新

为什么React useState依赖项在回调中为空?

为什么第一次在父回调函数中没有更新子状态值?

useState中的变量未在useEffect回调中更新

为什么 setState 回调会抛出错误:“来自 useState() 和 useReducer() 钩子的状态更新不支持第二个回调参数......”

react Hooks中useState更新器函数内的回调

回调中引用旧状态的useState状态更新

为什么 react useState 不更新值?

为什么在异步函数中未执行带有回调的函数?

理解为什么值不是 Rails 回调规范中的预期值

为什么我不能从 useEffect 回调中更新我的组件的状态?

如果函数是值,为什么回调函数不能是变量?

外部变量在成功回调中未正确更新

在setState回调中ReactJS状态未更新

回调中的组件属性更改时,绑定未更新

Plaid Link 中的 onSuccess 回调未更新

为什么@State值未更新

为什么我的回调没有在 Tensorflow 中调用?

为什么我不能在回调中调用useRef?

为什么此回调中的条件总是返回false?

为什么要在REST API中回调?

为什么在javascript中首先执行回调函数?

为什么“ this”指向回调函数中的“ window Object”?

为什么在回调中调用 ViewModel 会发生重组?

从 ag 网格中的回调更新单元格值

useState的值始终是地图事件回调中的初始值