我已经使用新的react钩子将近4个月了,这对创建react组件来说是一个很好的调整。目前,我正在尝试从类组件迁移到功能组件,但遇到了一些问题。例如,让我们讨论这个案例,并比较函数和类组件,以更好地理解这个问题。
class UserInformation extends React.Component {
state = {
isBusy: false,
};
updateImage = (uploadedImageData: IUploadImage): void => {
const imageData = {
ImageData: base64ToArrayBuffer(uploadedImageData.ImageData.ImageData),
FileName: uploadedImageData.FileName,
};
this.setState({ isBusy: true }, () => {
this.props.updateSettingsUserImage(this.props.selectedUser, imageData)
.then(() => this.setState({ isBusy: false }));
});
};
deleteImage = (): void => {
this.setState({ isBusy: true }, () => {
this.props.deleteSettingsUserImage(this.props.selectedUser)
.then(() => this.setState({ isBusy: false }));
});
};
const { selectedUser } = this.props;
return (
<BaseInfoCardHeader
withUploadableAvatar
style={{ margin: '0 -12px' }}
name={selectedUser.FullName}
deleteImage={this.deleteImage}
updateImage={this.updateImage}
photopath={selectedUser.Photopath}
/>
);
}
export default UserInformation;
这是UserInformation 的功能组件版本
const UserInformation=(props(=>{const[isBusy,setIsBusy]=useState(false(;
const updateImage = (uploadedImageData: IUploadImage): void => {
const imageData = {
ImageData: base64ToArrayBuffer(uploadedImageData.ImageData.ImageData),
FileName: uploadedImageData.FileName,
};
setIsBusy(true);
};
const deleteImage = (): void => setIsBusy(true);
useEffect(() => {
if (isBusy) {
updateSettingsUserImage(props.selectedUser, imageData)
.then(() => setIsBusy(false));
}
}, [isBusy]);
useEffect(() => {
if (isBusy) {
deleteSettingsUserImage(props.selectedUser)
.then(() => setIsBusy(false));
}
}, [isBusy]);
const { selectedUser } = this.props;
return (
<BaseInfoCardHeader
withUploadableAvatar
style={{ margin: '0 -12px' }}
name={selectedUser.FullName}
deleteImage={this.deleteImage}
updateImage={this.updateImage}
photopath={selectedUser.Photopath}
/>
);
}
export default UserInformation;
我们可以看到,在功能组件内部,无论是触发updateImage还是触发deleteImagemageData添加另一个状态,并在其useEffect依赖项列表中使用它。但是,如果我们没有imageData,并且一切都取决于是否繁忙,该怎么办。处理这种情况的最佳方法是什么?
为什么需要在这个组件中设置状态?还要注意,不要仅仅为了新颖性而将类组件转换为功能组件,基于类的组件仍然有自己的位置。但你的例子实际上是一个很好的候选者。
const UserInformation = ({props}) => {
const [isBusy, setBusy] = useState(false)
const updateImage = async (uploadedImageData: IUploadImage): void => {
setBusy(true);
const imageData = {
ImageData: base64ToArrayBuffer(uploadedImageData.ImageData.ImageData),
FileName: uploadedImageData.FileName,
};
await updateSettingsUserImage(props.selectedUser, imageData)
setBusy(false);
};
const deleteImage = async (): void => {
setBusy(true);
await deleteSettingsUserImage(props.selectedUser);
setBusy(false);
}
const { selectedUser } = props;
return (
<BaseInfoCardHeader
withUploadableAvatar
style={{ margin: '0 -12px' }}
name={selectedUser.FullName}
deleteImage={this.deleteImage}
updateImage={this.updateImage}
photopath={selectedUser.Photopath}
/>
);
}
export default UserInformation;