useReducer - keydown 处理程序重新评估每个渲染的初始状态
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当组件发现它需要重新渲染时,它的函数将再次运行。你所做的相当于询问为什么
每次 App 运行时都运行
getInitialState
,这相当于Which should make what's comebclear 。
这并不是说
useReducer
需要再次计算初始值 - 它不需要,它只在第一次运行时使用第二个参数来确定初始状态。您正在调用每次应用程序重新渲染时计算初始状态的函数。只要您确保计算初始状态的函数没有副作用,请随意忽略它 - 您现在所做的就很好。
另一种选择是将第三个参数传递给 useReducer 作为调用以计算初始状态的函数。
When a component sees that it needs to re-render, its function will run again. What you're doing is equivalent to asking why
runs
getInitialState
every time App runs, which is equivalent toWhich 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.您在每次渲染时调用 getInitialState,这并不意味着它正在重新初始化。
您可以通过在专为函数使用而设计的第三个参数位置运行初始化程序来避免这种情况。
您还应该在渲染函数之外为减速器创建函数,否则它会比应有的频率更频繁地重新运行。
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.