react-native - 从 ImagePicker 中选择时,图像显示速度极慢
问题描述
我一直无法弄清楚为什么在选择图像后需要 1-3 秒才能显示图片的问题。图像数组将不超过 4 个图像。
我将 useState 与数组一起使用以保存所有照片
// PHOTOS
const [photos, setPhotos] = useState([]);
当组件加载时。我使用useEffect
它来检查我们是否已授予选择图像,如下所示。
useEffect(() => {
(async () => {
if (Platform.OS !== "web") {
const { status } =
await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== "granted") {
alert("Sorry, we need camera roll permissions to make this work!");
}
}
})();
}, []);
接下来,我们有一个将运行该pickImage
功能的按钮。这负责获取选择的图像,查看它是否是主要的,然后将其添加到照片数组中。
const pickImage = async () => {
// Get the image from the phone
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsMultipleSelection: true,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
exif: true,
});
// Set the photo as primary as true or false
const photo = {
isPrimary: photos.length === 0 ? true : false,
url: result.uri,
};
// Update current primary
if (photo.isPrimary) {
setCurrentPrimary(photos.length);
}
// Add photo to the array
setPhotos([...photos, photo]);
};
最后,我们要确保我们可以看到这些正在添加的图像。我们使用一个FlatList
. 这是这样做的:
<FlatList
data={photos}
keyExtractor={(item) => item.url}
renderItem={({ item, index }) => {
return (
<View
key={index}
style={{
flexDirection: "row",
justifyContent: "space-between",
}}
>
<Text
style={{
alignContent: "center",
alignSelf: "center",
color: "white",
}}
>
{index + 1}
</Text>
<Image
source={{ uri: item.url }}
style={{
height: heightPercentageToDP(20),
width: widthPercentageToDP(40),
resizeMode: "contain",
}}
/>
<View
style={{
flexDirection: "row",
alignSelf: "center",
marginRight: 20,
justifyContent: "space-around",
}}
>
<View
style={{
color: item.isPrimary ? "red" : "blue",
}}
>
<Button
containerStyle={{
backgroundColor: item.isPrimary ? "red" : "",
}}
color={item.isPrimary ? "green" : ""}
title="Primary"
onPress={() => makePrimary(index)}
/>
</View>
<Button
color="red"
title="Remove"
onPress={() => removeImage(index)}
/>
</View>
</View>
);
}}
/>;
任何关于哪个部分可能导致长时间滞后的建议都非常感谢。还有为什么会这样。据我了解,仅包含 4 张图像的数组不应导致长时间滞后,并且应该几乎是即时的,尤其是在添加到数组时。
谢谢
解决方案
推荐阅读
- c# - 将一般的 ASP.NET 控件视为基于列表的控件(即 DropDownList、RadioButtonList 等)
- kubernetes - 使用 multus-cni 添加的 IP 地址无法从同一集群中的另一个 pod 访问
- rcpp - RcppArrayFire 中的随机洗牌
- python - 如何对两点之间的 x、y 和 z 进行线性插值?
- elixir - `mix hex.docs offline` 的输出结果为 EPUB 而不是 HTML
- php - 问题独白学说频道日志记录,symfony 4,与 php
- regex - 正则表达式提取方括号、逗号和引号 [] 之间的文本,"
- ruby-on-rails - Ruby On Rails:参数 - 允许:false
- c++ - 这是 std::gcd 中的错误吗?
- python - 运行 manage.py 时出现无法导入名称 urlresolvers 错误