Open arlyxiao opened 2 years ago
当出现组件无限重新渲染时,会报如下错误
Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
可能是由几种情况引起的
function App() { const [count, setCount] = useState(0); setCount(1); // infinite loop return }
State updates → triggers re-render → state updates → triggers re-render → …
fixed
function App() { const [count, setCount] = useState(0); useEffect(() => { setCount(1); }, []) return ... }
function App() { const [count, setCount] = useState(0); useEffect(() => { setCount(count + 1) // infinite loop }, [count]) return ... }
count updates → useEffect detects updated dependency → count updates → useEffect detects updated dependency → …
function App() { const [count, setCount] = useState(0); useEffect(() => { setCount(previousCount => previousCount + 1) }, []) return ... }
export default function App() { const [count, setCount] = useState(0); return ( <button onClick={setCount(1)}>Submit</button> // infinite loop ); }
export default function App() { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(1)}>Submit</button> // infinite loop ); }
https://alexsidorenko.com/blog/react-infinite-loop/
当出现组件无限重新渲染时,会报如下错误
可能是由几种情况引起的
Updating the state inside the render
State updates → triggers re-render → state updates → triggers re-render → …
fixed
Infinite loop in useEffect
count updates → useEffect detects updated dependency → count updates → useEffect detects updated dependency → …
fixed
Incorrectly set event handlers
State updates → triggers re-render → state updates → triggers re-render → …
fixed
https://alexsidorenko.com/blog/react-infinite-loop/