[英]How to stop the infinite loop inside this React useEffect?
我希望 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
最好的方法是將非 React 代碼集成到應用程序中,這樣設置 state 作為按鍵的結果是自然而微不足道的。
function App() {
const [keys, setKeys] = React.useState<string[]>([]);
useEffect(() => {
function handleKeypress(event: KeyboardEvent) {
setKeys([...keys, event.key]);
// There will be more code here that's unrelated to React.
}
document.addEventListener("keypress", handleKeypress);
return () => {
document.removeEventListener("keypress", handleKeypress);
};
}, []);
然后你可以完全放棄你當前的React.useEffect
(和它的無限循環)。
如果這不是一個選項,您將不得不從 React 外部觸發 React state setter - 無論您怎么看,這都會非常難看。 我想你可以將它分配給一個外部變量:
let setKeysOuter;
function handleKeypress(event: KeyboardEvent) {
setKeysOuter?.(keys => [...keys, event.key]);
// There will be more code here that's unrelated to React.
}
function App() {
const [keys, setKeys] = React.useState<string[]>([]);
setKeysOuter = setKeys;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.