首页 > 解决方案 > 从 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 张图像的数组不应导致长时间滞后,并且应该几乎是即时的,尤其是在添加到数组时。

谢谢

标签: react-nativereact-native-image-picker

解决方案


推荐阅读