gpt4 book ai didi

javascript - 超过 React-Redux 最大调用堆栈大小

转载 作者:行者123 更新时间:2023-12-03 14:00:10 26 4
gpt4 key购买 nike

我遇到错误超过最大调用堆栈大小。也许我以错误的方式理解 componentDidUpdate,但它不应该运行一次,而不是 1000 次。如何修复它?

class App extends Component {

constructor(props) {
super(props);
this.state = {
amount: 0
}
}

updateAmout() {
let number = 0;
this.props.comments.map((comment, index) => {

if (comment.replyTo === null) {

number += 1;
this.setState({amount: number});
}
return null;
});
}

componentWillMount() {
this.updateAmout();
}

componentDidUpdate() {
this.updateAmout();
}

render() {
console.log(this.state.amount);
return (
<div className="comments-container">
<div id="comments">
<AddComment />
<div className="comments-flow">
<div className="comments-header">
<div className="pull-right">
<a href="" className="text-muted">Best</a> |
<a href="" className="active">Newest</a> |
<a href="" className="text-muted">Oldest</a>
</div>
<b>6 Comments</b>
</div>
<RenderComments />
</div>
<button className="btn btn-block">More...</button>
</div>
</div>

) // return
} // render
} // App

最佳答案

每次修改 componentDidUpdate 中的状态时,都会异步引发重新渲染。在您的方法 updateAmount 中,您正在修改状态。并且您在 componentDidUpdate 中调用该方法,因此您启动了重新渲染的无限循环,因此创建的这个无限循环最终浪费了 javascript 内存。

更新状态时的 React 周期如下。这样你就很容易理解为什么会进入死循环了。 enter image description here

关于javascript - 超过 React-Redux 最大调用堆栈大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45022440/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com