我希望Reaction呈现来自非Reaction上下文的按键,更具体地说是字符串数组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