如何将 Promise 转换为字符串?我使用 Axios 和 return 数据到我的反应组件
How to convert Promise to String? I used Axios and return the data to my react Component
我在上传图片后 API 调用了 Cloudinary,它 return 是一个承诺而不是字符串。我想让我上传的图片上的 URL 保存在我的数据库中。
这是 return 屏幕截图:
这是我的 Axios 代码:
export const uploadImage = imageUpload => async dispatch => {
try {
const formData = new FormData();
formData.append('file', imageUpload);
const res = await axios.post(
'https://api.cloudinary.com/v1_1/frank/image/upload',
formData
);
return res.data.secure_url;
} catch (err) {
const errors = err.response.data.error;
}
};
我也试过使用 .then()
,但是我的变量 returns undefined
.
好的,我通过我的 redux thunk 发送我的 res
dispatch({
type: UPLOAD_SUCCESS,
payload: res.data.secure_url
});
然后在我的组件上使用 useEffect 挂钩来设置我的 formData。我还为我的道具使用了 useState 钩子
const [formData, setFormData] = useState({photo: '', imgURL: ''});
如果触发调度
useEffect(() => {
setFormData({ ...formData, photo: image });
}, [image]);
现在我的照片被设置为一个字符串。感谢您分享您的想法。有帮助。
我在上传图片后 API 调用了 Cloudinary,它 return 是一个承诺而不是字符串。我想让我上传的图片上的 URL 保存在我的数据库中。
这是 return 屏幕截图:
这是我的 Axios 代码:
export const uploadImage = imageUpload => async dispatch => {
try {
const formData = new FormData();
formData.append('file', imageUpload);
const res = await axios.post(
'https://api.cloudinary.com/v1_1/frank/image/upload',
formData
);
return res.data.secure_url;
} catch (err) {
const errors = err.response.data.error;
}
};
我也试过使用 .then()
,但是我的变量 returns undefined
.
好的,我通过我的 redux thunk 发送我的 res
dispatch({
type: UPLOAD_SUCCESS,
payload: res.data.secure_url
});
然后在我的组件上使用 useEffect 挂钩来设置我的 formData。我还为我的道具使用了 useState 钩子
const [formData, setFormData] = useState({photo: '', imgURL: ''});
如果触发调度
useEffect(() => {
setFormData({ ...formData, photo: image });
}, [image]);
现在我的照片被设置为一个字符串。感谢您分享您的想法。有帮助。