小道具を変更しても、コンポーネントの再レンダリングに問題がありました。フォトアルバムの状態とその中の新しい写真のアップロードを処理するレデューサー(下)がありました。
const profilePhotoReducer = (state={
fetching: false,
photos: [],
dataSetChanged: false,
uploading: false
},action)=>{
console.log('reducer called: ', action.type);
switch (action.type){
case "PHOTOS_FETCHING":
return{
...state,
fetching: true
};
case "PHOTOS_FETCH_SUCCESS":
return {
...state,
fetching: false,
photos: action.payload,
dataSetChanged: false
};
case "PHOTOS_FETCH_FAILED":
return {
...state,
fetching: false,
dataSetChanged: false
};
case "UPLOADING":
return {
...state,
uploading: true
};
case "UPLOAD_SUCCESS":
return {
...state,
dataSetChanged: true,
uploading: false
};
case "UPLOAD_FAILED":
return {
...state,
uploading: false
};
default:
return state;
}
};
export default profilePhotoReducer;
写真のアップロードが成功した後、「UPLOAD_SUCCESS」action.typeが一致し、dataSetChanged(Boolean)が反転し、コンポーネント(以下)で次のように処理します。
class ProfilePhotosComponent extends React.Component{
componentDidMount(){
console.log('********------***********: ', this.props.profilePhoto.dataSetChanged);
if(this.props.profilePhoto.photos.length === 0 || this.props.profilePhoto.dataSetChanged){
this.props.getPhotos();
}
}
render(){
const PhotoList = this.props.profilePhoto.photos.map((photo, i)=>{
return (<PhotoComponent name={photo} key={i}/>);
});
return (
<div className={'card pcard'}>
<div className={'col-md-12'}>
<UploadPhotoForm handleUpload={this.props.handleUpload}/>
{PhotoList}
</div>
</div>
);
}
}
function mapStateToProps(state){
return {
profilePhoto: state.profilePhoto
};
}
function mapDispatchToProps(dispatch){
return bindActionCreators({
getPhotos,
handleUpload
},dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(ProfilePhotosComponent);
重要なのは、componentDidMount
コンポーネントがマウントされた後に関数が1回だけ呼び出され、その後、小道具が変更された場合、コンポーネントは再レンダリングされますが、写真は再度フェッチされないため、違いは見られません。必要なものはcomponentWillReceiveProps
componentWillReceiveProps(nextProps) {
console.log('********------***********: ', nextProps.profilePhoto.dataSetChanged);
if(this.props.profilePhoto.dataSetChanged !== nextProps.profilePhoto.dataSetChanged) {
if(nextProps.profilePhoto.photos.length === 0 || nextProps.profilePhoto.dataSetChanged){
this.props.getPhotos();
}
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加