React 应该组件更新太多的递归

React shouldComponentUpdate too much recursion

本文关键字:太多 递归 更新 组件 React      更新时间:2023-09-26

我正在使用 React 构建一个每隔几秒钟自动更新一次的仪表板。我从 Ajax 调用中获取属性并将它们传递给组件,到目前为止一直工作正常。

在其中一个组件中,我需要设置每 x 秒自动更新一次的图像源,但在这种情况下,我需要使用 state。

这是我的组件:

var ImageContainer = React.createClass({
    getInitialState: function(){
        return { src: this.props.initialImage};
    },
    shouldComponentUpdate: function(nextProps, nextState){
        this.setState({ src: this.props.initialImage });
        return true;
    },  
    render: function() {
        return (
            <div className="col-md-8 col-sm-12 nopadding post-image vcenter" >
                <img src={this.state.src} className="img-responsive center-cropped"/>
            </div>
        );
    }
});

这很好用,但给too much recursion error.

进行了搜索并找到了这个答案,建议使用componentWillReceiveProps来设置状态,但是当我使用它时,图像不会在第一个自动刷新时更新,只会在第二个上更新。

这是我实现componentWillReceiveProps后的当前流程:

  • Ajax 收到调用结果,假设数据 A
  • 调用状态传递给两个组件,即图像和文本
  • 初始调用>> 图像数据 A、文本数据 A
  • 组件刷新以获取数据 B>>图像数据 A、文本数据 B
  • 组件刷新以获取数据 C>> 图像数据 B、文本数据 C

。等等。你能帮我理解为什么会这样吗?

注意:我需要使用状态,因为需要对组件DidMount运行检查以确认图像有效

我过去在componentWillReceiveProps上遇到过类似的问题。假设如果它被称为它有新的道具,似乎情况并非总是如此。

请参阅:https://facebook.github.io/react/blog/2016/01/08/A-implies-B-does-not-imply-B-implies-A.html

递归可能是由于在shouldComponentUpdate中设置状态而不返回 false 以停止渲染。可能值得尝试如下内容:

shouldComponentUpdate: function(nextProps, nextState) {
   this.setState({ src: nextProps.initialImage });
   return nextProps.initialImage !== this.props.initialImage;
}

通过添加一个条件,将旧的 props 和状态与其替换进行比较,它应该停止递归。

注意:我无法测试此代码,所以也许关闭