Javascript 上传图像后在react native中获取下载URL
我有一个上传图像功能:Javascript 上传图像后在react native中获取下载URL,javascript,firebase,react-native,expo,firebase-storage,Javascript,Firebase,React Native,Expo,Firebase Storage,我有一个上传图像功能: const [profileURL, setProfileURL] = useState("") uploadImage = async (uri, userUID) => { const response = await fetch(uri) const blob = await response.blob() var ref = firebase.storage().ref()
const [profileURL, setProfileURL] = useState("")
uploadImage = async (uri, userUID) => {
const response = await fetch(uri)
const blob = await response.blob()
var ref = firebase.storage().ref().child("avatar/" + userUID)
await ref.put(blob, {contentType:'image/jpg'}).catch((error) => {
console.log(error);
})
await ref.getDownloadURL().then((url) => {
setProfileURL(url)
})
}
const handleSubmit = async () => {
await this.uploadImage(imageOne, firebase.auth().currentUser?.uid).then(
setCurrentUserDetails(
{ ...currentUserDetails,
name,
age: Number(age),
height,
profileURL,
}
)
);
}
上载部分正在工作,图像已正确保存到firebase存储,但我正在尝试获取图像的下载url,并将其设置为状态setProfileURL({uri:url})
然后调用handleSubmit函数,该函数调用此上载函数:
const [profileURL, setProfileURL] = useState("")
uploadImage = async (uri, userUID) => {
const response = await fetch(uri)
const blob = await response.blob()
var ref = firebase.storage().ref().child("avatar/" + userUID)
await ref.put(blob, {contentType:'image/jpg'}).catch((error) => {
console.log(error);
})
await ref.getDownloadURL().then((url) => {
setProfileURL(url)
})
}
const handleSubmit = async () => {
await this.uploadImage(imageOne, firebase.auth().currentUser?.uid).then(
setCurrentUserDetails(
{ ...currentUserDetails,
name,
age: Number(age),
height,
profileURL,
}
)
);
}
其他所有内容都已更新,但此profileURL字段未更新。当我在uploadImage函数中记录状态变量时,我得到以下结果:
setProfileURL in upload function [Function bound dispatchAction]
profileURL in upload function
我已尝试setProfileURL(字符串(url))
,但无法保存此DonwnloadURL
我还尝试:
uploadImage = async (uri, userUID) => {
const response = await fetch(uri)
const blob = await response.blob()
var ref = firebase.storage().ref().child("avatar/" + userUID)
await ref.put(blob, {contentType:'image/jpg'}).catch((error) => {
console.log(error);
})
const url = await ref.getDownloadURL().catch((error) => {
console.log(error);
})
console.log("URL", url);
setProfileURL(String(url))
return url
}
哪个会注销正确的url:
URL https://firebasestorage.googleapis.com/MY_URL_HERE
只是似乎没有更新状态?状态更新不同步。从 setState()并不总是立即更新组件。可能 批处理或将更新推迟到以后。这使得阅读成为一种状态 就在调用setState()之后,这是一个潜在的陷阱。相反,使用 componentDidUpdate或设置状态回调(设置状态(更新程序、, 回调),其中任何一个都保证在更新后触发 已应用。如果需要根据上一个设置设置状态 状态,请阅读下面的更新程序参数 因此,在
setCurrentUserDetails
之前,profileURL
不会更新。第二种方法应该可以获得正确的URL。但是,您可以直接使用方法返回的url值,而不是使用profileURL
const handleSubmit = async () => {
const url = await this.uploadImage(
imageOne,
firebase.auth().currentUser?.uid
);
setCurrentUserDetails({
...currentUserDetails,
name,
age: Number(age),
height,
profileURL: url,
});
};