【问题标题】:How to retrieve image from firebase in react native expo?如何在 react native expo 中从 firebase 检索图像?
【发布时间】:2021-09-06 07:04:37
【问题描述】:

我是 React Native 的新手,仍在边做边学。我已经在 firebase 中上传了我想在第二个屏幕上显示的图像。虽然,我不断收到类似的错误

can't find variable: profileImageUrl 

我正在尝试检索下一页上的图像。

这是上传到firebase的代码:

const uploadImage = async () => {
  const blob = await new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function () {
      resolve(xhr.response);
    };
    xhr.oneerror = function () {
      reject(new TypeError('Network request failed'));
    };
    xhr.responseType = 'blob';
    xhr.open('GET', image, true);
    xhr.send(null);
  });

  const ref = firebase.storage().ref().child('/ankit/');

  const snapshot = ref.put(blob);

  snapshot.on(
    firebase.storage.TaskEvent.STATE_CHANGED,
    () => {
      setUploading(true);
    },

    (error) => {
      setUploading(false);
      console.log(error);
      blob.close();
    },
    () => {
      snapshot.snapshot.ref.getDownloadURL().then((url) => {
        setUploading(false);
        console.log('downlaod url', url);
        return url;
      });
    }
  );
};

这里是检索代码:

const [Image, setImage] = useState(false);

let imageRef = firebase.storage().ref('/ankit/');
imageRef
  .getDownloadURL()
  .then((url) => {
    setImage({ profileimageUrl: 'url' });
  })
  .catch((e) => console.log('getting downloadURL of image error => ', e));

return (
  <View>
    <Image source={this.state.profileImageUrl}></Image>
  </View>
)

【问题讨论】:

    标签: javascript firebase react-native expo


    【解决方案1】:

    您应该重构显示图像的代码。您正在使用新的钩子状态来存储状态,但尝试在 html 中使用旧的反应状态语法的语法。应该是这样的:

    const [image, setImage] = useState(false);
    
    useEffect(() => {
      let imageRef = firebase.storage().ref('/ankit/');
      imageRef
        .getDownloadURL()
        .then((url) => {
          setImage(url);
        })
        .catch((e) => console.log('getting downloadURL of image error => ', e));
    },[])
    
    return (
      <View>
        <Image src={image}></Image>
      </View>
    );
    

    【讨论】:

    • 非常感谢@Tarik Huber 这工作没有任何错误,但新屏幕没有任何图片。虽然我可以在火力基地中看到它。
    • 您能否尝试运行更新后的代码。也许您只是忘记将其放入useEffect
    • 得到这个错误:警告:失败的道具类型:无效的道具source提供给Image
    • 我觉得应该是src。我已经更新了答案。
    • 感谢您的回答,但收到此错误“ 组件需要source 属性而不是src。”
    猜你喜欢
    • 2020-06-30
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    相关资源
    最近更新 更多