简体   繁体   English

Firebase 不刷新图像(反应)

[英]Firebase Not Refreshing Image (React)

I am using firebase with react to store images so that the user can upload them there and then have them be displayed and I manage to display the uploaded image but when I refresh the page.我正在使用 firebase 对存储图像做出反应,以便用户可以将它们上传到那里然后显示它们,并且我设法显示上传的图像但是当我刷新页面时。 The image gets removed, my function userProfileImage() does not seem to update the image, how can I keep the image?图像被删除,我的 function userProfileImage() 似乎没有更新图像,我该如何保留图像?

  const [image, setImage] = useState(null);
  const [url, setUrl] = useState("");
  const [progress, setProgress] = useState(0);

  const handleChange = e => {
    if (e.target.files[0]) {
      setImage(e.target.files[0]);
    }
  };

  const userProfileImage = () => {
    updateProfile(auth.currentUser, {
      //old image
      photoURL: <Avatar sx={{ width: 250, height: 250 }} />
    }).then(() => {
      // Profile updated!
      <Avatar src={url} sx={{ width: 250, height: 250 }} />
    }).catch((error) => {
      // An error occurred
      console.log(error);
    });
  }
    
 

  const handleUpload = () => {
    const uploadTask = 
    storage.ref(`images/${image.name}`).put(image);
    uploadTask.on(
      "state_changed",
      snapshot => {
        const progress = Math.round(
          (snapshot.bytesTransferred / snapshot.totalBytes) * 100
        );
        setProgress(progress);
      },
      error => {
        console.log(error);
      },
      () => {
        storage
          .ref("images")
          .child(image.name)
          .getDownloadURL()
          .then(url => {
            setUrl(url);
          });
      }
    );
    userProfileImage();
  };

  return (
    <div className='App'>
    <Header/>
    <br />
    <br />
    {progress > 0 && progress < 100 ?
    <progress value={progress} max="100" /> : <div></div>
    }
    <div class="proPic">
    <Avatar src={url} sx={{ width: 250, height: 250 }} />
    <input type="file" onChange={handleChange} />
    <button onClick={handleUpload}>Submit</button>
    </div>
    </div>
  )
}

When you are refreshing, all the components will also be refreshed.当你刷新时,所有的组件也会被刷新。 As a result all the states will be reinitialized.结果,所有状态都将重新初始化。 So when you refresh, url will be null again.因此,当您刷新时,url 将再次变为 null。 So you should retrieve the image when the component is refreshed.因此,您应该在刷新组件时检索图像。 You can retrive the uploaded image inside a useEffect hook.您可以在 useEffect 挂钩中检索上传的图像。

useEffect(()=>{
//retrieve image
},[]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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