useReducer - keydown 处理程序重新评估每个渲染的初始状态

发布于 2025-01-10 06:57:55 字数 1290 浏览 0 评论 0原文

https://codesandbox.io/s/suspicious-chebyshev-vy4mf2

useReducer 挂钩和 useEffect 以及 keydown 事件处理程序。问题是,在处理键盘按钮按下而导致的每次重新渲染时,组件函数都会重新运行获取初始状态的函数。

可见的错误结果是每次渲染时在控制台中记录的随机数(我希望没有记录)。换句话说,这里的目标是停止在每个渲染上运行 getInitialState 函数。

import { useEffect, useReducer } from "react";
import "./styles.css";

interface IAction {
  type: string;
  payload: string;
}

export default function App() {
  const reducer = (state: string, action: IAction) => {
    switch (action.type) {
      case "KEYDOWN":
        return action.payload;
      default:
        return state;
    }
  };

  const getInitialState = () => {
    const rand = Math.random().toString();
    console.log(rand);
    return rand;
  };

  const [state, dispatch] = useReducer(reducer, getInitialState());

  const keyDownHandler = (e: KeyboardEvent): void => {
    dispatch({
      type: "KEYDOWN",
      payload: e.key
    });
  };

  useEffect(() => {
    document.addEventListener("keydown", keyDownHandler);
    return () => document.removeEventListener("keydown", keyDownHandler);
  }, [state, dispatch]);

  return <div className="App">{state}</div>;
}

https://codesandbox.io/s/suspicious-chebyshev-vy4mf2

I have a useReducer hook and useEffect with a keydown event handler. The issue is that on each re-render resulting from handling the keyboard button press, the component function re-runs the function obtaining initial state.

The visible incorrect result is the random number logged in console on each render (I expect no logging). In other words, the goal here is to stop getInitialState function running on every render.

import { useEffect, useReducer } from "react";
import "./styles.css";

interface IAction {
  type: string;
  payload: string;
}

export default function App() {
  const reducer = (state: string, action: IAction) => {
    switch (action.type) {
      case "KEYDOWN":
        return action.payload;
      default:
        return state;
    }
  };

  const getInitialState = () => {
    const rand = Math.random().toString();
    console.log(rand);
    return rand;
  };

  const [state, dispatch] = useReducer(reducer, getInitialState());

  const keyDownHandler = (e: KeyboardEvent): void => {
    dispatch({
      type: "KEYDOWN",
      payload: e.key
    });
  };

  useEffect(() => {
    document.addEventListener("keydown", keyDownHandler);
    return () => document.removeEventListener("keydown", keyDownHandler);
  }, [state, dispatch]);

  return <div className="App">{state}</div>;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝梦月影 2025-01-17 06:57:55

当组件发现它需要重新渲染时,它的函数将再次运行。你所做的相当于询问为什么

export default function App() {
  // ...
  const [state, dispatch] = useReducer(reducer, getInitialState());

每次 App 运行时都运行 getInitialState ,这相当于

export default function App() {
  // ...
  const parameterToPass = getInitialState();
  const [state, dispatch] = useReducer(reducer, parameterToPass);

Which should make what's comebclear 。

这并不是说 useReducer 需要再次计算初始值 - 它不需要,它只在第一次运行时使用第二个参数来确定初始状态。您正在调用每次应用程序重新渲染时计算初始状态的函数。

只要您确保计算初始状态的函数没有副作用,请随意忽略它 - 您现在所做的就很好。

另一种选择是将第三个参数传递给 useReducer 作为调用以计算初始状态的函数。

const [state, dispatch] = useReducer(reducer, null, getInitialState);

When a component sees that it needs to re-render, its function will run again. What you're doing is equivalent to asking why

export default function App() {
  // ...
  const [state, dispatch] = useReducer(reducer, getInitialState());

runs getInitialState every time App runs, which is equivalent to

export default function App() {
  // ...
  const parameterToPass = getInitialState();
  const [state, dispatch] = useReducer(reducer, parameterToPass);

Which should make what's going on clear.

It's not that useReducer needs to calculate the initial value again - it doesn't, it only uses that second parameter the first time it runs, to determine the initial state. It's that you're calling the function that calculates the initial state every time the App re-renders.

As long as you make sure the function that calculates the initial state doesn't have side-effects, feel free to just ignore it - what you're doing now is just fine.

Another option is to pass a third argument to useReducer as the function to invoke to calculate the initial state.

const [state, dispatch] = useReducer(reducer, null, getInitialState);
若有似无的小暗淡 2025-01-17 06:57:55

您在每次渲染时调用 getInitialState,这并不意味着它正在重新初始化。

您可以通过在专为函数使用而设计的第三个参数位置运行初始化程序来避免这种情况。

您还应该在渲染函数之外为减速器创建函数,否则它会比应有的频率更频繁地重新运行。

const { useEffect, useReducer } = React;

interface IAction {
  type: string;
  payload: string;
}
const reducer = (state: string, action: IAction) => {
  switch (action.type) {
    case "KEYDOWN":
      return action.payload;
    default:
      return state;
  }
};
function App() {
  const getInitialState = () => {
    const rand = Math.random().toString();
    console.log(rand);
    return rand;
  };

  const [state, dispatch] = useReducer(reducer, null, getInitialState);

  const keyDownHandler = (e: KeyboardEvent): void => {
    dispatch({
      type: "KEYDOWN",
      payload: e.key
    });
  };

  useEffect(() => {
    document.addEventListener("keydown", keyDownHandler);
    return () => document.removeEventListener("keydown", keyDownHandler);
  }, [state, dispatch]);

  return <div className="App">{state}</div>;
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
    <div id="root"></div>

You were calling the getInitialState on every render, that doesn't mean it was getting re-initialized.

You can avoid this by running the initializer in the 3rd argument position which is designed for function usage.

You should also create the function for the reducer outside of the render function, otherwise it re-runs more often than it should.

const { useEffect, useReducer } = React;

interface IAction {
  type: string;
  payload: string;
}
const reducer = (state: string, action: IAction) => {
  switch (action.type) {
    case "KEYDOWN":
      return action.payload;
    default:
      return state;
  }
};
function App() {
  const getInitialState = () => {
    const rand = Math.random().toString();
    console.log(rand);
    return rand;
  };

  const [state, dispatch] = useReducer(reducer, null, getInitialState);

  const keyDownHandler = (e: KeyboardEvent): void => {
    dispatch({
      type: "KEYDOWN",
      payload: e.key
    });
  };

  useEffect(() => {
    document.addEventListener("keydown", keyDownHandler);
    return () => document.removeEventListener("keydown", keyDownHandler);
  }, [state, dispatch]);

  return <div className="App">{state}</div>;
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
    <div id="root"></div>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文