[英]Why does app crash when page starts to load due to useEffect hook with firebase upload in React Native
我正在嘗試將照片上傳到我的帖子屏幕/頁面中的 firebase 存儲。 我以為我應該在調用 api 時使用 useEffect 鈎子,所以我這樣做了,並為必須更改以進行重新渲染的兩個狀態放入了一個依賴數組。 When I delete the useEffect and just have the uploadImage function and then I run the uploadImage function in the imagePicker function after confirming the event wasn't cancelled, it works but I can't seem to get the folder/imagename right. 我只能稱它為某事,然后它繼續覆蓋。
工作流程應該在屏幕上呈現兩個按鈕,當按下照片選擇器按鈕時,運行 chooseFromLibrary function,它將為 imageFilename 和 imageSelected(uri) 設置 state。 這應該告訴依賴數組運行調用帶有 imageSelected 和 imageFilename 變量的 uploadImage function 的效果。 我希望 uploadImage function 中的 ref 創建/放入 user.username 的文件夾(這是來自上下文),然后圖像名稱為 imageFilename 但它似乎不起作用。
我究竟做錯了什么?
const [user] = useContext(UserContext);
const [imageSelected, setImageSelected] = useState("");
const [imageFilename, setImageFilename] = useState("");
useEffect(() => {
uploadImage(imageSelected, imageFilename)
.then(() => {
Alert.alert("Success");
})
.catch((error) => {
Alert.alert(error);
});
}, [imageFilename, imageSelected]);
const uploadImage = async (uri, name) => {
const response = await fetch(uri);
const blob = await response.blob();
var ref = firebase
.storage()
.ref()
.child(`${user.username}` + name);
return ref.put(blob);
};
const chooseFromLibrary = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.cancelled) {
let fileArray = result.uri.split("/");
let name = fileArray.pop();
setImageFilename(name);
setImageSelected(result.uri);
}
}
如果尚未選擇圖像,我必須運行 if 語句返回效果。
if (!imageSelected) {
return;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.