[英]React.js (useState ,useEffect) infinite loop error when setState("updated value") is called
import React, {useState,useEffect} from 'react';
import ReactDOM from 'react-dom';
import reportWebVitals from './reportWebVitals';
function AppTwo(props){
const [state, setState] = React.useState("initial value");
useEffect(() => {
console.log(`useEffect: ${state}`);
},[state]);
setState("updated value");
console.log(state);
return `<h1>${state}</h1>`;
}
ReactDOM.render(
<>
<AppTwo />
</>,
document.getElementById('root')
);
Error: Too many re-renders.错误:重新渲染过多。 React limits the number of renders to prevent an infinite loop.
React 限制了渲染的数量以防止无限循环。
Don't call setState
inside of the component body.不要在组件主体内部调用
setState
。 It will update every time the component re-renders.每次组件重新渲染时都会更新。 That's why you are getting an infinite loop of state updates.
这就是为什么您会获得 state 更新的无限循环。
WORKS!作品!
import React, {useState,useEffect} from 'react';
import ReactDOM from 'react-dom';
import reportWebVitals from './reportWebVitals';
function AppTwo(props){
const [state, setState] = React.useState("initial value");
useEffect(() => {
console.log(`useEffect: ${state}`);
// document.getElementById('btn').innerHTML = `<h1>State: ${state}</h1>`;
},[state]);
console.log(state);
return (
<>
<h1>State: {state}</h1>
<button id="btn" onClick={() => {setState('updated value')}}>
click
</button>
</>
)
}
ReactDOM.render(
<>
<AppTwo />
</>,
document.getElementById('root')
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.