簡體   English   中英

為什么我必須 select 2 次(不同的照片)才能在 firebase 存儲中顯示圖像

[英]Why I have to select 2 times (different photo) for displaying image in firebase storage

當我第一次單擊上傳圖像時,它會顯示加載影響,但甚至不顯示任何背景圖像以進行上傳,然后我必須上傳不同的圖像以顯示圖像,然后再將 go 提交到顯示我的帳戶的 Newfeed 頁面。所以我不確定,因為我的我必須配置一些規則的代碼或 firebase 服務。 謝謝你幫助我

import { useCookies } from "react-cookie";
import {
  ref, uploadBytesResumable, getDownloadURL, getStorage
} from "firebase/storage";
import styled from "styled-components";

const Avatar = styled.div`
width: 250px;
height: 250px;
border-radius: 50%;
background-size: cover;
background-position: center;
cursor: pointer;
`;

function Photo() {
  const [cookies] = useCookies(["userName"]);
  const [image, setImage] = useState(null);
  const [url, setUrl] = useState("./images/UploadPic.svg");

  const handleChange = (e) => {
    if (e.target.files[0]) {
      setImage(e.target.files[0]);
      const storage = getStorage();
      const storageRef = ref(storage, `images/${cookies.userName}`);
      const uploadTask = uploadBytesResumable(storageRef, image);

      uploadTask.on(
        "state_changed",
        () => {
          setUrl("./loading.gif");
        },
        (error) => {
          switch (error.code) {
            case "storage/unauthorized":
              console.log("storage is unauthorized");
              break;
            case "storage/canceled":
              console.log("storage is canceled");
              break;
            case "storage/unknown":
              console.log("storage is unknown");
              break;
            default:
              console.log("sorry it is not about storage");
          }
        },
        () => {
          getDownloadURL(storageRef).then((url) => {
            setUrl(url);
          });
        },
      );
    }
  };

  return (
    <div style={{ alignSelf: "center" }}>
      <label htmlFor="file-input">
        <Avatar style={{ backgroundImage: `url(${url})` }} />
      </label>
      <input id="file-input" type="file"  accept="image/*" onChange={handleChange} />
    </div>
  );
}

export default Photo;
<input id="file-input" type="file"  accept="image/*" onChange={handleChange} />

嘿,請嘗試將上面的行更改為下面

<input id="file-input" type="file"  accept="image/*" onChange={() => handleChange()} />

不確定是否值得嘗試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM