Return 来自异步箭头函数的 JSX
Return JSX from async arrow function
它必须是基本的,但请帮助我理解为什么这不起作用。
当我写一个普通的箭头函数和 return jsx 时,它可以工作。但是,当我对 return jsx 使用具有相同箭头功能的 async/await 请求时,它失败了。
编辑:
实际上我必须在列表视图中显示用户的个人资料图片。因此,我正在调用此函数来检索我的 render() {return }
块
中各个用户的图像
这个有效
handleProfilePhoto = firstName => {
return (
<img
className="comment-img"
src={require("../../../../Webroot/images/dashboard/image3.png")}
alt={firstName + " profile"}
/>
);
};
而这不是
handleProfilePhoto = async (firstName) => {
let err = false;
await Axios
.get(MY_URL)
.then(function () {
err = false;
})
.catch(function () {
err = true;
});
return err === true ? (
<img
className="comment-img"
src={require("../../../../Webroot/images/dashboard/image3.png")}
alt={firstName + " profile"}
/>
) : (
<img
className="comment-img"
src={require("../../../../Webroot/images/dashboard/image4.png")}
alt={firstName + " profile"}
/>
);
};
请不要将 .then()
与 async / await
一起使用,您要么使用链接方式,要么使用异步方式。
handleProfilePhoto = async (firstName) => {
let err = false;
try {
await Axios.get(MY_URL);
} catch(err) {
err = true;
}
return err === true ? (
<img
className="comment-img"
src={require("../../../../Webroot/images/dashboard/image3.png")}
alt={firstName + " profile"}
/>
) : (
<img
className="comment-img"
src={require("../../../../Webroot/images/dashboard/image4.png")}
alt={firstName + " profile"}
/>
);
};
此外,handleProfilePhoto
returns 一个承诺。
handleProfilePhoto.then(result => {
//your result is here
})
它必须是基本的,但请帮助我理解为什么这不起作用。
当我写一个普通的箭头函数和 return jsx 时,它可以工作。但是,当我对 return jsx 使用具有相同箭头功能的 async/await 请求时,它失败了。
编辑:
实际上我必须在列表视图中显示用户的个人资料图片。因此,我正在调用此函数来检索我的 render() {return }
块
这个有效
handleProfilePhoto = firstName => {
return (
<img
className="comment-img"
src={require("../../../../Webroot/images/dashboard/image3.png")}
alt={firstName + " profile"}
/>
);
};
而这不是
handleProfilePhoto = async (firstName) => {
let err = false;
await Axios
.get(MY_URL)
.then(function () {
err = false;
})
.catch(function () {
err = true;
});
return err === true ? (
<img
className="comment-img"
src={require("../../../../Webroot/images/dashboard/image3.png")}
alt={firstName + " profile"}
/>
) : (
<img
className="comment-img"
src={require("../../../../Webroot/images/dashboard/image4.png")}
alt={firstName + " profile"}
/>
);
};
请不要将 .then()
与 async / await
一起使用,您要么使用链接方式,要么使用异步方式。
handleProfilePhoto = async (firstName) => {
let err = false;
try {
await Axios.get(MY_URL);
} catch(err) {
err = true;
}
return err === true ? (
<img
className="comment-img"
src={require("../../../../Webroot/images/dashboard/image3.png")}
alt={firstName + " profile"}
/>
) : (
<img
className="comment-img"
src={require("../../../../Webroot/images/dashboard/image4.png")}
alt={firstName + " profile"}
/>
);
};
此外,handleProfilePhoto
returns 一个承诺。
handleProfilePhoto.then(result => {
//your result is here
})