我有一个组件接收图像作为道具,对它们执行一些计算,因此我需要更新它的类。但是如果我在计算后使用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 :(得分:1)
您应该将您的逻辑放入componentWillReceiveProps(https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops),以便在渲染发生之前进行道具转换。
答案 1 :(得分: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>
);
}
}