簡體   English   中英

我在傳遞縮略圖值時使用 firebase 存儲的反應代碼出現錯誤,它在 object 上具有名稱屬性,錯誤 givin

[英]I'm getting error in my react code im using firebase storage while im passing the thumbnail value and it has name property on that object, error givin

` 使用表單.js:

import { projectStorage } from '../firebase/config';
import { useAuth } from './useAuth';

export const useForm = () => {
  const { user } = useAuth();
  const uploadImage = async (thumbnail) => {
    const uploadPath = `thumbnails/${user.uid}/${thumbnail.name}`;
    try {
      const img = await projectStorage.ref(uploadPath).put(thumbnail);
      const imgUrl = await img.ref.getDownloadURL();
    } catch (err) {
      console.log(err.message);
    }
  };
  return { uploadImage };
};`

表單.jsx:`

   import { useState } from "react"
import { useForm} from '../hooks/useForm'

export default function Form() {
    const [caption, setCaption] = useState('')
    const [error, setError] = useState(null)
    const [thumbnail, setThumbnail] = useState(null)
    const { uploadImage} = useForm()

        const handleSubmit = (e) =>{
            e.preventDefault()
          uploadImage(thumbnail)
        }
        
    const handleChange = (e) =>{
        setThumbnail(null)
        const selected = e.target.files[0]
        console.log(selected);
        
        if(!selected){
            setError('please select a file')
            return
        }   
        if(!selected.type.includes('image')){
            setError('please select a image file')
            return
        }

        setError(null)
        setThumbnail(selected)
        console.log('photo updated');
    }

   
  return (
    <div className="add-form">
        <form onClick={handleSubmit}>
            <label>
                <span>Photo:</span>
                <input type="file"  name="file" id="file"  onChange={handleChange} required/>
            </label>
            <label >
                <span>caption:</span>
                <textarea name="captiom" id="caption" onChange={(e)=>setCaption(e.target.value)}></textarea>
                { error && <p className="error">{Error}</p>}
            </label>
            <button>Submit</button>
        </form>
    </div>
  )
}

` 以上是我在 useForm.js 中的代碼,我使用存儲在 form.jsx 中的縮略圖 state 並通過 function 傳遞給 useForm.js,因此我可以使用它創建路徑以在 firebase 存儲中上傳圖像。

useForm.js:7 Uncaught (in promise) TypeError: Cannot read properties of null (reading 'name') 得到這個錯誤

有人可以幫我解決我做錯的事請給我解決方案

看起來這是因為您沒有驗證thumbnail是否實際設置在handleSubmit function 中。

所以當它到達這一行時:

const uploadPath = `thumbnails/${user.uid}/${thumbnail.name}`;

...它無法讀取.name ,因為thumbnail是 null。


嘗試處理將thumbnail提交為null的情況,如下所示:

const handleSubmit = (e) =>{
  e.preventDefault();
  if(!thumbnail){
    setError('please select a file');
    return;
  }
  setError(null);
  uploadImage(thumbnail);
}

暫無
暫無

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

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