2016-09-07 42 views
0

我有一個組件接收圖像作爲道具,對它們進行一些計算,結果我需要更新它的類。但是如果在計算之後使用setState,我會收到警告,我不應該更新狀態......我應該如何重組這個問題?React.js - 根據道具計算後的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> 
     ); 
    } } 

回答

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> 
    ); 
    } 
} 
+0

這是不好的做法是應該this.props.images更新smallImgsWidthClass不會因爲它在構造函數中設置。如上所述,您應該使用componentWillReceiveProps。 – quoo