gpt4 book ai didi

reactjs - 运行 setState prop 函数hang 最大调用堆栈

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

在我的模板 js 上,我有以下内容

 updateBarTitle(title){
this.setState({barTItle:title});
}
render() {
const childrenWithProps = React.Children.map(this.props.children, function (child) {
var childProps = {
updateBarTitle: this.updateBarTitle.bind(this)
};
var childWithProps = React.cloneElement(child, childProps);
return childWithProps;
}, this);

还有我的 child 。

 componentDidUpdate(){
this.props.updateBarTitle('Users');
}

测试应用程序时,一旦状态发生变化,我的浏览器就会卡住很长时间,然后返回超出最大调用堆栈大小 需要一些关于我做错了什么的建议。

最佳答案

您正在使用子 componentDidUpdate() 方法创建无限循环。它调用 updateBarTitle(),调用 setState(),重新渲染,再次调用 updateBarTitle()...等等.

如果您希望在 componentDidUpdate() 方法中使用该逻辑,则需要添加一些条件,以便它只调用一次。

您可以将 barTitle 的当前状态作为 Prop 传递给子级,然后执行以下操作:

if(this.props.barTitle !== 'Users') {
this.props.updateBarTitle('Users');
}

例如,阻止循环发生。

编辑:这里给出一个更清晰的例子是 DEMO以此来说明。

关于reactjs - 运行 setState prop 函数hang 最大调用堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37352877/

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