【问题标题】:React.js - setState after calculation based on propsReact.js - 基于 props 计算后的 setState
【发布时间】:2016-09-07 16:51:36
【问题描述】:

我有一个组件接收图像作为道具,对它们执行一些计算,因此我需要更新它的类。但是如果我在计算后使用setState,我会收到警告说我不应该更新状态......我应该如何重组这个?

class MyImageGallery extends React.Component { 

    //[Other React Code]

    getImages() {
       //Some calculation based on this.props.images, which is coming from the parent component
       //NEED TO UPDATE STATE HERE?
    }

    //componentWillUpdate()? componentDidUpdate()? componentWillMount()? componentDidMount()? {

      //I CAN ADD CLASS HERE USING REF, BUT THEN THE COMPONENT'S
      // FIRST RENDERED WITHOUT THE CLASS AND IT'S ONLY ADDED LATER
    }


    render() {

        return (
            <div ref="galleryWrapper" className={GET FROM STATE????} 
                <ImageGallery
                    items={this.getImages()}
                />
            </div>
        );
    } }

【问题讨论】:

    标签: reactjs setstate


    【解决方案1】:

    您应该将您的逻辑放入 componentWillReceiveProps (https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops) 以便在渲染发生之前进行道具转换。

    【讨论】:

      【解决方案2】:

      最终我们做的是在构造函数中运行逻辑,然后将类置于初始状态:

      class MyImageGallery extends React.Component { 
      
       constructor(props) {
              super(props);
              this.getImages = this.getImages.bind(this);
              this.images = this.getImages();
              this.state = {smallImgsWidthClass: this.smallImgsWidthClass};
          }
      
      getImages() {
         //Some calculation based on this.props.images, which is coming from the parent component
          this.smallImgsWidthClass = '[calculation result]';
          return this.props.images;
      }
      
      render() {
      
          return (
              <div className={this.state.smallImgsWidthClass } 
                  <ImageGallery
                      items={this.images}
                  />
              </div>
          );
         }
       }
      

      【讨论】:

      • 这不是一个好习惯,因为 this.props.images 更新 smallImgsWidthClass 不会像构造函数中设置的那样。您应该使用上面提到的 componentWillReceiveProps。
      猜你喜欢
      • 2019-09-21
      • 2018-05-04
      • 2021-05-13
      • 2014-11-17
      • 1970-01-01
      • 1970-01-01
      • 2018-01-13
      • 1970-01-01
      • 2016-02-09
      相关资源
      最近更新 更多