我设置了一个在 return 中触发循环反应的回调,但我不明白为什么?

I set a callback that in return trigger a loop reaction and I cant see why?

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

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

child 发回结果如下:

 ---
    this.list = React.createRef();
    
    componentDidMount() {
    const { onSetMasonryHeight } = this.props;
     setTimeout(() => {
        onSetMasonryHeight(this.list.current.clientHeight);
     }, 50);
   }
  ---

这项工作我得到了 clientHeight 但这只有 运行 一次因此 componentDidMount()

所以我在以下方面做同样的事情:componentDidUpdate() 因为在每个 render() 之后我需要 clientHeight

...
      componentDidUpdate() {
        const { onSetMasonryHeight } = this.props;
        setTimeout(() => {
            onSetMasonryHeight(this.list.current.clientHeight);
        }, 50);
      }
...

并且在 parent Component 中我设置了这个 clientHeight

---
    onSetMasonryHeight = val => {
        this.setState(() => {
            return { masonryHeight: val };
        });
    };
...

现在循环是 运行ning 但奇怪的是应用程序正在运行,我可以看到 clientHeight 值是预期值但是笔记本电脑变得越来越暖和我的上帝我必须拉plugg 哈哈。

我使用断点进行调试,我看到 render() 在循环中同时在 mother 和 child 上触发,它看起来像 parent 方法 onSetMasonryHeight = val => {.. return 也在 child 上触发 setState() render(),这会创建循环。

有ide吗?或者我怎样才能做得更好?

将您的 componentDidUpdate 更改为:

componentDidUpdate(prevProps, prevState) {
  if (prevState.masonryHeight !== this.state.masonryHeight) {
  const { onSetMasonryHeight } = this.props;
    setTimeout(() => {
        onSetMasonryHeight(this.list.current.clientHeight);
    }, 50);
 }
}
  • 你必须在调用 setState 之前检查状态是否发生变化,否则你会得到无限的状态更新,这会给你的笔记本电脑带来麻烦