【发布时间】:2022-11-29 13:41:10
【问题描述】:
我希望 React 从非 React 上下文呈现按键,更具体地说是字符串数组 keys:
import * as React from "react";
import { render } from "react-dom";
let keys: string[] = [];
function handleKeypress(event: any) {
keys.push(event.key);
console.log(keys);
// there will be more code here unrelated to React.
}
document.removeEventListener("keypress", handleKeypress);
document.addEventListener("keypress", handleKeypress);
function App() {
const [keysState, setKeysState] = React.useState<string[]>([]);
React.useEffect(() => {
function updateKeysState() {
setKeysState([...keys]);
}
// if you uncomment this, the code inside useEffect will run forever
// updateKeysState()
console.log("Hello world");
}, [keysState]);
return (
<div>
{keys.map((key: string, id) => (
<li key={id}>{key}</li>
))}
</div>
);
}
const rootElement = document.getElementById("root");
render(<App />, rootElement);
我几乎完成了……问题是,React.useEffect 中的代码在无限循环中运行。
我认为将 [keysState] 作为第二个参数传递给 React.useEffect 会停止无限循环。但它没有。
为什么会这样以及如何解决?
直播码:https://codesandbox.io/s/changing-props-on-react-root-component-forked-eu16oj?file=/src/index.tsx
【问题讨论】:
-
这回答了你的问题了吗? Infinite loop in useEffect
-
@Layhout 我认为它比那个帖子更微妙
标签: javascript reactjs typescript