Firebase Storage和React Native,无法正确调用以动态值为参数的refFromURL()

6vl6ewon  于 12个月前  发布在  React
关注(0)|答案(1)|浏览(102)

我正在为在线订单构建一个简单的React Native移动的应用程序。我将所有产品相关信息存储在Firestore文档中作为字段(名称,价格,图像URL等)。我将图像存储在Firebase Storage中。当我想要创建图像引用时,我使用

const imageRef = storage().refFromURL('gs://testapp-1x2y3z.firebase.com/pics/TestImage.jpg');

字符串
该程序也可以正确使用静态字符串值。但是,当我想从Firestore文档字段读取ImageURL时,例如。

const assortmentRef = firestore().collection('Test_Store').doc('Assortment');,
    imageRef = storage().refFromURL(assortmentRef.ImageURL);


属性的字符串值,

assortmentRef.ImageURL


它的价值

gs://testapp-1x2y3z.firebase.com/pics/TestImage.jpg I


假设这个问题是因为React式原生有异步操作。有人有解决方案吗?我的目标是输入动态值,我可以从文档字段而不是静态URL派生。错误消息:

Possible Unhandled Promise Rejection (id: 45):
    Error: firebase.storage().refFromURL(*) 'url' must be a string value and begin with 'gs://' or 'https://'.


完整代码:

const ReadAssortment = ({ navigation }) => {
  const [shoeData, setShoeData] = useState([]);

  const fetchData = async () => {
    const assortmentRef = firestore().collection('Test_Store').doc('Assortment');
    const shoesCollection = assortmentRef.collection('Shoes');

    try {
      const querySnapshot = await shoesCollection.get();
      const dataPromises = [];

      querySnapshot.forEach((doc) => {
        const imgURL = doc.data().pictureURL;
        console.log(imgURL);
        
        const imageRef = storage().refFromURL(imgURL);

        dataPromises.push(
          imageRef.getDownloadURL().then((url) => ({
            ...shoeData,
            imageUri: url,
          }))
        );
      });

      const shoeDataWithImages = await Promise.all(dataPromises);
      setShoeData(shoeDataWithImages);
    } catch (error) {
      console.error('Error fetching:', error);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <View style={styles.container}>
      {shoeData.map((shoe, index) => (
        <View key={index}>
          <Text>Name: {shoe.Name}</Text>
          <Text>Price: {shoe.Preis}</Text>
          <Text>Info: {shoe.InfoText}</Text>
          {shoe.imageUri && <Image source={{ uri: shoe.imageUri }} style={styles.image} />}
        </View>
      ))}
      <Button title="Back" onPress={() => navigation.goBack()} />
    </View>
  );
};


问候,鲍勃
是的,我试图解析单引号和双引号内的ImageURL值,但它根本不起作用。我将非常感谢任何解决方案的建议。

ctehm74n

ctehm74n1#

如果我正确理解你的问题,你需要获取Firestore文档。
使用const assortmentRef = firestore().collection('Test_Store').doc('Assortment');,您只需定义DocumentReference
您需要调用此DocumentReferenceget()方法,如文档中所述:沿着以下行(使用async/await语法,而文档显示了then()语法)

const assortmentRef = firestore().collection('Test_Store').doc('Assortment');
const docSnap = await assortmentRef.get()
if (docSnap.exists) {
    const imageURL = doc.data().ImageURL;
    const imageRef = storage().refFromURL(imageURL);
    // ...
} else {
    // doc.data() will be undefined in this case
    console.log("No such document!");
}

字符串

相关问题