我有一個組件接收圖像作爲道具,對它們進行一些計算,結果我需要更新它的類。但是如果在計算之後使用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>
);
} }
這是不好的做法是應該this.props.images更新smallImgsWidthClass不會因爲它在構造函數中設置。如上所述,您應該使用componentWillReceiveProps。 – quoo