2016-09-07 13 views
0

私は小道具として画像を受け取り、その上で何らかの計算を行い、その結果、その階級を更新する必要があるコンポーネントを持っています。しかし、計算後にsetStateを使用した場合、私はまだ状態を更新すべきではないという警告を受け取ります...これをどのように再構成するべきですか?React.js - 小道具に基づいて計算した後のsetSt

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

答えて

1

前小道具の移行を行うに発生レンダリングするようにあなたはcomponentWillReceiveProps(https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops)にあなたのロジックを置く必要があります。これはないだろうthis.props.images smallImgsWidthClassを更新する必要がありますように良い習慣ではありません

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

これはコンストラクタで設定されているためです。上記のようにcomponentWillReceivePropsを使用する必要があります。
+0

:我々はコンストラクタでロジックを実行し、初期状態にクラスを入れたなかったものを最後に – quoo

関連する問題