UseState 变量在函数内设置后未更新 - React Native
UseState variable not updating after setting it within a function - React Native
为什么当我设置 URL(value) 或 setURL(val) 时它实际上并没有设置状态?
只有当我第二次按下上传按钮时,它才会正确设置状态..
第一次运行:
我的初始化状态:
const [URL, setURL] = useState();
获取下载地址的函数:
await getDownloadURL(fileRef).then((val)=>{
console.log("From function: "+val)
var value = val;
setURL(value)
}).catch((error)=>{
Alert.alert(error.message);
});
上传按钮功能:
我的代码:
const AddPost = () => {
const [isEnabled, setIsEnabled] = useState(false);
const toggleSwitch = () => setIsEnabled(previousState => !previousState);
const [Color, setColor] = useState('')
const [Desc, setDesc]= useState('');
const [location, setlocation] = useState('');
const navigation = useNavigation()
const [image, setImage] = useState(null);
const [URI, setURI] = useState(Result);
const [Result, setResult] = useState();
const [URL, setURL] = useState();
const [uploading, setUploading] = useState(false);
const usersCollectionRef = collection(db, "Posts");
const createPost = async () =>
{
setUploading(true);
let url = await uploadImageAsync(URI);
console.log("from upload btn: "+URL)
await addDoc(usersCollectionRef, { username: auth.currentUser?.email, Colour: Color, Injured: value2, Type: value3, Collar: isEnabled ? 'Yes' : 'No', Welfare: value4, status: value, Description: Desc, picture: URL, location: location })
Alert.alert("Successfully uploaded!");
navigation.navigate('MainScreen');
setUploading(false);
};
const TakeImage = async () => {
let result = await ImagePicker.launchCameraAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
quality: 0.6,
});
if (!result.cancelled) {
setImage(result.uri);
setURI(result.uri);
}
};
const BrowseImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
quality: 0.6,
});
console.log(result);
if (!result.cancelled) {
setImage(result.uri);
setURI(result.uri);
}
};
const uploadImageAsync =async(uri)=> {
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function (e) {
console.log(e);
reject(new TypeError("Network request failed"));
};
xhr.responseType = "blob";
xhr.open("GET", uri, true);
xhr.send(null);
});
const fileRef = ref(getStorage(), uuid.v4());
const result = await uploadBytes(fileRef, blob);
let url = await getDownloadURL(fileRef).then((val)=>{
console.log("From function: "+val)
setURL(val);
return val;
}).catch((error)=>{
Alert.alert(error.message);
});
return url;
}
由于更新状态是一种异步方法,因此状态不会立即更新。你必须像这样解决 -
const uploadImageAsync =async(uri)=> {
// rest of your code
let url = await getDownloadURL(fileRef).then((val)=>{
console.log("From function: "+val)
setURL(val);
return val;
}).catch((error)=>{
Alert.alert(error.message);
});
return url;
}
然后在你的 onPress 函数中:-
const createPost = async () => {
let url = await uploadImageAsync(URI);
// Rest of your code
}
为什么当我设置 URL(value) 或 setURL(val) 时它实际上并没有设置状态?
只有当我第二次按下上传按钮时,它才会正确设置状态..
第一次运行:
我的初始化状态:
const [URL, setURL] = useState();
获取下载地址的函数:
await getDownloadURL(fileRef).then((val)=>{
console.log("From function: "+val)
var value = val;
setURL(value)
}).catch((error)=>{
Alert.alert(error.message);
});
上传按钮功能:
我的代码:
const AddPost = () => {
const [isEnabled, setIsEnabled] = useState(false);
const toggleSwitch = () => setIsEnabled(previousState => !previousState);
const [Color, setColor] = useState('')
const [Desc, setDesc]= useState('');
const [location, setlocation] = useState('');
const navigation = useNavigation()
const [image, setImage] = useState(null);
const [URI, setURI] = useState(Result);
const [Result, setResult] = useState();
const [URL, setURL] = useState();
const [uploading, setUploading] = useState(false);
const usersCollectionRef = collection(db, "Posts");
const createPost = async () =>
{
setUploading(true);
let url = await uploadImageAsync(URI);
console.log("from upload btn: "+URL)
await addDoc(usersCollectionRef, { username: auth.currentUser?.email, Colour: Color, Injured: value2, Type: value3, Collar: isEnabled ? 'Yes' : 'No', Welfare: value4, status: value, Description: Desc, picture: URL, location: location })
Alert.alert("Successfully uploaded!");
navigation.navigate('MainScreen');
setUploading(false);
};
const TakeImage = async () => {
let result = await ImagePicker.launchCameraAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
quality: 0.6,
});
if (!result.cancelled) {
setImage(result.uri);
setURI(result.uri);
}
};
const BrowseImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
quality: 0.6,
});
console.log(result);
if (!result.cancelled) {
setImage(result.uri);
setURI(result.uri);
}
};
const uploadImageAsync =async(uri)=> {
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function (e) {
console.log(e);
reject(new TypeError("Network request failed"));
};
xhr.responseType = "blob";
xhr.open("GET", uri, true);
xhr.send(null);
});
const fileRef = ref(getStorage(), uuid.v4());
const result = await uploadBytes(fileRef, blob);
let url = await getDownloadURL(fileRef).then((val)=>{
console.log("From function: "+val)
setURL(val);
return val;
}).catch((error)=>{
Alert.alert(error.message);
});
return url;
}
由于更新状态是一种异步方法,因此状态不会立即更新。你必须像这样解决 -
const uploadImageAsync =async(uri)=> {
// rest of your code
let url = await getDownloadURL(fileRef).then((val)=>{
console.log("From function: "+val)
setURL(val);
return val;
}).catch((error)=>{
Alert.alert(error.message);
});
return url;
}
然后在你的 onPress 函数中:-
const createPost = async () => {
let url = await uploadImageAsync(URI);
// Rest of your code
}