Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 运行setState prop函数挂起最大调用堆栈_Reactjs - Fatal编程技术网

Reactjs 运行setState prop函数挂起最大调用堆栈

Reactjs 运行setState prop函数挂起最大调用堆栈,reactjs,Reactjs,在我的模板js中,我有以下内容 updateBarTitle(title){ this.setState({barTItle:title}); } render() { const childrenWithProps = React.Children.map(this.props.children, function (child) { var childProps = { updateBarTitle: this.up

在我的模板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);
还有我的孩子

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

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

您正在使用子
componentdiddupdate(
)方法创建一个无限循环。它调用
updateBarTitle()
,调用
setState()
,重新呈现,再次调用
updateBarTitle()
,依此类推

如果希望在componentDidUpdate()方法中包含该逻辑,则需要添加一些条件,使其只调用一次

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

if(this.props.barTitle !== 'Users') {
  this.props.updateBarTitle('Users');
}
例如,阻止循环发生


编辑:为了给出一个更清晰的例子,这里有一个例子来说明。

感谢您对发生这种情况的原因的解释,我将
componentdiddupdate()
更改为
componentdiddmount
,一切似乎都正常。然而,我担心我犯了一个不可预见的错误。
componentDidMount()
不会以同样的方式持续触发
componentdiddupdate()
会,但出于同样的原因,通常还是不鼓励这样做。如果可以的话,您应该在更新中添加一个停止条件或重新构造您的逻辑。您能推荐我的方法吗?
ComponentDidMount
的目的是在加载组件时使用新值更新布局组件。我可能正在尝试
组件willmount
,但是正如您所说的,这可能也会被阻止。现在理解了,谢谢您的帮助!