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 に答える