示例代码:
export default function Cart() {
const navigation = useNavigation();
// Stores the selected image URI
const [file, setFile] = useState('');
// Stores any error message
const [error, setError] = useState(null);
// Function to pick an image from
//the device's media library
const pickImageAsync = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
quality: 1,
});
if (!result.canceled) {
console.log(result);
setFile(result.assets[0].uri);
} else {
alert('You did not select any image.');
}
};
return (
<View style={styles.container}>
<TouchableOpacity onPress={() =>pickImageAsync() } style={styles.btnContainer} ><View><Text style={styles.textview}>Upload Image</Text>
</View>
</TouchableOpacity>
{/* Conditionally render the image
or error message */}
{file ? navigation.navigate('AddToCart',{'file':file}): (
// Display an error message if there's
// an error or no image selected
<Text style={styles.errorText}>{error}</Text>
)}
</View>
);
}
我正在使用 ImagePicker 库将图像发送到另一个屏幕 与屏幕导航器。它存储在状态变量中。然而它是 给我一个错误,它无法在渲染时更新组件 另一个组件。我必须将相同的图像文件传递给多个 组件从一个组件到另一个组件。我只有一个上传按钮 选择 ,需要将图像发送到另一个组件,我 正在通过route.params获取。
我意识到它无法同时更新图像和发送, 我该如何解决这个问题
这是一个不好的方法,建议您对某些操作进行导航,在您的情况下可以是当您从选择器获取文件并且没有文件更新错误文本时
const navigation = useNavigation();
// Stores the selected image URI
const [file, setFile] = useState('');
// Stores any error message
const [error, setError] = useState(null);
// Function to pick an image from
//the device's media library
const pickImageAsync = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
quality: 1,
});
//todo set error if don't have file
if (!result.canceled) {
console.log(result);
setFile(result.assets[0].uri);
navigation.navigate('AddToCart',{'file':file})
} else {
alert('You did not select any image.');
}
};
return (
<View style={styles.container}>
<TouchableOpacity onPress={() =>pickImageAsync() } style={styles.btnContainer} >
<View><Text style={styles.textview}>Upload Image</Text>
</View>
</TouchableOpacity>
{!file ? <Text style={styles.errorText}>{error}</Text> : null}
</View>
);
}
一切就绪!