ฉันสามารถจัดเก็บหรือแคชรูปภาพในเครื่องใน React Native ได้หรือไม่

ฉันมีแอปข่าวและฉันต้องการจัดเก็บภาพไว้ในเครื่องเมื่อได้รับครั้งแรก

AsyncStorage ของ React Native ยอมรับข้อมูลสตริงคีย์-ค่า ฉันสามารถใช้มันได้หรือไม่?

ในเบราว์เซอร์ ฉันใช้ canvas เพื่อรับข้อมูล uri หรือBlobBuilder เพื่อรับ BLOB ไม่แน่ใจว่าใช้งานได้ใน React Native หรือไม่


person Brick Yang    schedule 03.02.2016    source แหล่งที่มา


คำตอบ (1)


คุณสามารถทำได้ด้วยวิธีต่อไปนี้:

const STORAGE_KEY = 'yourkey';

Api.getImages()           // Replace Api.getImages() with your data source.
  .then((data) => {

    var images = data; 

    // Set a key for AsyncStorage, and Stringify the data
    AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(data))

    this.setState({
      images : images,
    });

  })

จากนั้นดึงออกมาดังนี้:

AsyncStorage.getItem(STORAGE_KEY)
  .then((storedData) => {
    var parsedData = JSON.parse(storedData)  
    // do something with the parsedData
  })
  .catch((err) => {
    // Could set the AnsyncStorage key here since it was not found.
  })
person Nader Dabit    schedule 03.02.2016
comment
ขอบคุณ. คุณช่วยบอกรายละเอียดเพิ่มเติมเกี่ยวกับ Api.getImages() และ data ให้ฉันหน่อยได้ไหม - person Brick Yang; 04.02.2016
comment
แน่นอนว่าฉันแค่ใช้สิ่งนั้นเป็นฟังก์ชันทั่วไปที่ดึงข้อมูลจาก API บางตัว คุณแนะนำให้แอปรับรูปภาพจากที่ไหนสักแห่ง ดังนั้น โดยพื้นฐานแล้วคุณสามารถแทนที่ฟังก์ชัน Api.getImages() ด้วยฟังก์ชันใดก็ตามที่คุณใช้เพื่อรับข้อมูลของคุณได้ - person Nader Dabit; 04.02.2016
comment
คุณหมายถึงเราควรจัดเก็บข้อมูลในรูปแบบ Base64 ใช่หรือไม่ เราจะแปลงรูปภาพได้ทันทีเป็น Base64 ได้อย่างไร - person Ivan Chernykh; 15.06.2016