2016-09-07 5 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

Смежные вопросы