0

我有一个组件接收图像作为道具,对它们执行一些计算,因此我需要更新它的类。但是如果我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>
        );
    } }
4

2 回答 2

1

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

于 2016-09-07T16:56:01.857 回答
0

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

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>
    );
   }
 }
于 2016-09-08T08:39:46.463 回答