它必须是基本的,但是请帮助我理解为什么它不起作用。
当我编写一个普通的箭头函数并返回jsx时,它可以工作。但是,当我使用带有相同箭头功能的async / await请求返回jsx时,它将失败。
编辑:
实际上,我必须在列表视图中显示用户的个人资料图像。因此,我正在调用此函数来检索我的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"}
/>
);
};
答案 0 :(得分:1)
请不要将.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
返回一个诺言。
handleProfilePhoto.then(result => {
//your result is here
})