简体   繁体   中英

React Native CameraRoll.getPhotos API doesn't seem to return

图像网格

I want to create an image grid like this one but I have failed to get camera roll from the device. I have tried using @react-native-community/cameraroll but it doesn't seem to work Here is my code.

import React,{useState, useEffect} from 'react';
import {View} from 'react-native';
import * as Permissions from 'expo-permissions';
import CameraRoll from "@react-native-community/cameraroll";

const getImages = async (setImages) => {
   await Permissions.askAsync(Permissions.CAMERA_ROLL);
   const x=await CameraRoll.getPhotos({first:2})
   await setImages([...x.edges])
}

export default function App() {
  const [images,setImages]=useState([])
  useEffect(() => {
    console.log('loading photos')
    getImages(setImages)
    console.log('back')
    console.log(images)
  }, []);
  return (
    <View >
    </View>
  );
} 

The code is intended to load images into the state when the component mounts. How can I fix this problem?

You should probably use Expo MediaLibrary instead of CameraRoll.

You can try this code:

import React, { useState, useEffect } from 'react';
import { View, Image } from 'react-native';
import * as Permissions from 'expo-permissions';
import * as MediaLibrary from 'expo-media-library';

const getImages = () => {
  return Permissions.askAsync(Permissions.CAMERA_ROLL)
    .then(() => {
      return MediaLibrary.getAssetsAsync({ first: 2 });
    })
    .then((result) => {
      return result.assets;
    });
};

export default function App() {
  const [images, setImages] = useState([]);

  useEffect(() => {
    console.log('loading photos');
    getImages().then(setImages);
    console.log('back');
    console.log(images);
  }, []);

  return (
    <View>
      { images.map((image) => (
        <Image key={image.id} source={{ uri: image.uri }} style={{width: 200, height: 200}}/>
      ))}
    </View>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM