Reactjs 我设置了一个回调,作为回报触发循环反应,我不明白为什么?

Reactjs 我设置了一个回调,作为回报触发循环反应,我不明白为什么?,reactjs,callback,Reactjs,Callback,我学习了Reactjs,现在我有一个循环,不知道为什么。程序运行,但笔记本电脑越来越热,我设置了断点,看到代码运行了很多次 我有两个Reactjs组件,我创建了一个回调onSetMasonryHeight(),并将其发送到子组件中 子系统返回的结果如下所示: --- this.list = React.createRef(); componentDidMount() { const { onSetMasonryHeight } = this.props;

我学习了Reactjs,现在我有一个
循环
,不知道为什么。程序运行,但笔记本电脑越来越热,我设置了断点,看到代码运行了很多次

我有两个Reactjs
组件
,我创建了一个回调
onSetMasonryHeight()
,并将其发送到子组件中

子系统返回的结果如下所示:

 ---
    this.list = React.createRef();
    
    componentDidMount() {
    const { onSetMasonryHeight } = this.props;
     setTimeout(() => {
        onSetMasonryHeight(this.list.current.clientHeight);
     }, 50);
   }
  ---
这项工作我得到了
clientHeight
,但它只运行一次,因此
componentDidMount()

所以我在:
componentdiddupdate()
中也这样做,因为在每次
render()之后,我都需要
clientHeight

...
      componentDidUpdate() {
        const { onSetMasonryHeight } = this.props;
        setTimeout(() => {
            onSetMasonryHeight(this.list.current.clientHeight);
        }, 50);
      }
...
在parent
Component
中,我设置了这个
clientHeight

---
    onSetMasonryHeight = val => {
        this.setState(() => {
            return { masonryHeight: val };
        });
    };
...
现在循环正在运行,但奇怪的是,应用程序正在运行,我可以看到
clientHeight
值是预期值,但笔记本电脑越来越热,我的天啊,我必须拉插头

我使用断点进行调试,我看到
render()
在一个循环中同时在母对象和子对象上触发,它看起来像父方法
onSetMasonryHeight=val=>{..
有一个
返回值
也在子对象上触发
setState()
render()
,这就创建了循环


任何ide?或者我如何才能做得更好?

将您的组件更新为:

componentDidUpdate(prevProps, prevState) {
  if (prevState.masonryHeight !== this.state.masonryHeight) {
  const { onSetMasonryHeight } = this.props;
    setTimeout(() => {
        onSetMasonryHeight(this.list.current.clientHeight);
    }, 50);
 }
}
  • 在调用setState之前,您必须检查状态是否发生了更改。否则,您将获得无限状态更新,这将给您的笔记本电脑带来灾难