我尝试直接在返回值中更新状态,而不使用任何生命周期方法,但收到如下错误:
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
我提到了this link对于上述错误,但我没有得到合适的解决方案。是否总是需要使用函数或生命周期方法来更新状态?
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;
我编写了上面的代码并收到错误,但在控制台中状态值正在更新并多次打印。
最佳答案
出现此错误是因为每次渲染组件时
setState
都会触发组件的重新渲染。这会导致更新的无限循环。setState() will always lead to a re-render unless shouldComponentUpdate() returns false.
是的,需要使用函数或者生命周期方法来更新状态。您不得直接在渲染函数中更新状态。您应该在渲染之前准备好要渲染的数据,并且应该在生命周期方法或回调中更新状态。
关于javascript - 尝试使用react组件返回中的setstate更新状态并获取 "Maximum update depth exceeded error"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56217440/