[英]How to achieve an async function chain with await when the functions are parent and child?
I have a profile editor component (parent) and a cropper component (child).我有一个配置文件编辑器组件(父)和一个裁剪器组件(子)。 I want to update a database with two async actions awaiting each other.
我想用两个等待对方的异步操作来更新数据库。 These are: 1.) a dispatch from the parent, which has form fields, and 2.) a dispatch from the cropper, which has an image blob.
它们是:1.) 来自具有表单字段的父级的调度,以及 2.) 来自具有图像 blob 的裁剪器的调度。 At the moment I have a parent file, a child file, and an actions file.
目前我有一个父文件、一个子文件和一个动作文件。
relevant snippet from parent:来自父母的相关片段:
handleSubmit = e => {
e.preventDefault();
// Dispatches action to update database with form fields
this.props.accountSettingsUpdateProfile(this.state);
};
relevant snippet from child:孩子的相关片段:
onClickSave = () => {
if (this.editor) {
this.editor.getImageScaledToCanvas().toBlob(blob => {
// Dispatches an action to upload database with new cropped image
this.props.uploadProfileImage(blob);
});
And in my actions file I have something like:在我的操作文件中,我有类似的内容:
export const accountSettingsUpdateProfile = settings => async () => {//etc}
export const uploadProfileImage = file=> async () => {//etc}
I would like to have something like:我想要类似的东西:
Parent家长
handleSubmit = e => {
e.preventDefault();
// Dispatches action to update database with form fields
this.props.dispatchParentFieldsAndChildBlobToActions();
};
Actions行动
try {
//Both try update, if either error logged to console.
} catch (error) {
console.log(error)
}
The crux of it is, I don't know how to consolidate these actions.关键是,我不知道如何巩固这些行动。 I could achieve what I want by just cutting the cropper component out and pasting it into it's parent instead of having it as a separate component, but that's cheating.
我可以通过将裁剪器组件切出并将其粘贴到它的父组件而不是将其作为单独的组件来实现我想要的,但这是作弊。
An alternate approach would be like this.另一种方法是这样的。 Save child and parents relevant states to redux store then call your actions upon a button click or something in parent or child whenever you need it.
将孩子和父母的相关状态保存到 redux 商店,然后在您需要时在父母或孩子中单击按钮或其他内容时调用您的操作。
your parent or child components您的父或子组件
handlSubmit=()=>{
this.props.saveMyProfile((info)=>console.log(info)); //you can passs a callback if you wish
}
Actions.js Actions.js
export const saveMyProfile = (callback) => async (dispatch, getState) => {
try {
const profileData= getState().profile.data; //get data from your redux store
const blob= getState().profile.blob;
if (!profileData || !blob){
callback("either profile data or blob is empty");
return;
}
const response = await axios.get(baseURL, { profileData,blob });
// console.log("data: ", response.data);
dispatch({ type: SET_PROFILE_DATA, payload: null });
callback("profile has been successfully updated!");
} catch (err) {
console.log(err);
callback("error occured!");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.