我在组件重新渲染方面遇到了问题,甚至改变了道具。我有一个reducer(下面),它处理相册的状态并上传任何新照片。
K#Inner =:= V
成功上传照片后,' UPLOAD_SUCCESS' action.type匹配并翻转dataSetChanged(布尔值)和我的组件(下面)我以这种方式处理它:
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;
答案 0 :(得分:1)
问题是componentDidMount
函数只在组件安装后被调用一次,之后如果道具发生变化,你的组件会被重新渲染,但你的照片不会被再次提取,因此你看不到差异,你需要的是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();
}
}
}
答案 1 :(得分:0)
在mapStateToProps
中,我发现您没有dataSetChanged
这样返回。
function mapStateToProps(state){
return {
dataSetChanged: state. dataSetChanged
};
}
更新道具时不会调用ComponentDidMount,您必须使用componentWillReceiveProps()
或直接将该属性绑定到render
函数中的JSX元素。