[英]Trying to update the state using setstate inside the return in react component and getting “Maximum update depth exceeded error”?
I'm trying to update the state directly inside the return without using any of the life cycle method and am getting error like this: 我试图不使用任何生命周期方法而直接在返回值内部更新状态,并得到如下错误:
Maximum update depth exceeded.
超过最大更新深度。 This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.
当组件重复调用componentWillUpdate或componentDidUpdate内部的setState时,可能会发生这种情况。 React limits the number of nested updates to prevent infinite loops.
React限制了嵌套更新的数量,以防止无限循环。
I referred to this link for the above error, but I didn't get an appropriate solution. 我针对此错误引用了此链接 ,但没有得到适当的解决方案。 Is it always necessary to use a function or life cycle method to update the state?
是否总是需要使用函数或生命周期方法来更新状态?
import React, { Component } from "react";
import "./App.css";
class App extends Component {
state = {
name: "john"
};
render() {
console.log(this.state);
return (
<div className="App">
<header className="App-header">
{this.state.name}
{this.setState({ name: "abc" })}
</header>
</div>
);
}
}
export default App;
I wrote the above code and am getting the error but in console the state value is getting update and printing it in many times. 我编写了上面的代码,但出现错误,但是在控制台中,状态值多次更新并打印出来。
You have this error because setState
triggers re-render of the component each time when your component renders. 您有此错误,因为
setState
每次在组件渲染时都会触发组件的重新渲染。 This causes an endless loop of updates. 这将导致无休止的更新循环。
setState() will always lead to a re-render unless shouldComponentUpdate() returns false.
除非shouldComponentUpdate()返回false,否则setState()将始终导致重新渲染。
Yes, it is necessary to use a function or life cycle method to update the state. 是的,有必要使用函数或生命周期方法来更新状态。 You must not update a state directly in a render function.
您不得直接在渲染函数中更新状态。 You should prepare your data for rendering before render and you should update a state in lifecycle methods or in callbacks.
您应在渲染之前准备好要渲染的数据,并应在生命周期方法或回调中更新状态。
This is because you are using setState
inside the render
method. 这是因为您正在
render
方法中使用setState
。 You cannot use setState
inside the render
method because it will cause the Component to re-render again and again. 您不能在
render
方法内使用setState
,因为它将导致Component一次又一次地重新渲染。 Because in react application a Component get re-rendered only if Props pass to that component or when setState
is called. 因为在React应用程序中,仅当Props传递给该组件或调用
setState
时才重新渲染Component。
So you can use
componentDidMount
life-cycle to set the state.因此,您可以使用
componentDidMount
生命周期设置状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.