未处理的拒绝 (FirebaseError):使用无效数据调用函数 addDoc()

问题描述

import React,{ useContext,useState } from 'react'
import "./style.css";
import { SignInBtn } from '../../componenets'
import { UserContext} from '../../contexts/user';
import AddAPhotoIcon from '@material-ui/icons/AddAPhoto';
import makeId from '../../helper/functions';
import { storage,db } from '../../firebase';
import firebase from "firebase";


export default function CreatePost() {
    const [user,setUser] = useContext(UserContext).user;
    const [caption,setCaption] = useState("");

    const [image,setimage] = useState(null);

    const [progress,setProgress] = useState(0);

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

            var selectedImageSrc=URL.createObjectURL(e.target.files[0]);
        
            var imagePreview =  document.getElementById("image-preview");

            imagePreview.src=selectedImageSrc;
            imagePreview.style.display="block";
        }

    };

    const handleUpload =() => {
        if(image){
            var imageName = makeId(10);
            const uploadTask=storage.ref(`images/${imageName}.jpg`).put(image);

            uploadTask.on("state_changed",(snapshot) =>{
                // progress function

                const progress=Math.round((snapshot.bytesTransferred/snapshot.totalBytes)*100);

                setProgress(progress);
            },(error) => {
                console.log(error);
            },() => {
                //get download url and upload the post info

             storage
            .ref("images")
            .child(`${imageName}.jpg`)
            .getDownloadURL()
            .then((imageUrl) => {

                   db.collection("posts").add({
                    timestamp: firebase.firestore.FieldValue.serverTimestamp(),caption:caption,photoUrl: imageUrl,username: user.email.replace("@gmail.com",""),profileUrl: user.photoUrl

                });
                })
            });
        }
    }; //handle upload check image exist

    return (
        <div className = "createPost">
           
        {user ? (
            <div className ="createPost__loggedIn">
            <p> Create Post </p>
            <div className ="createPost__loggedInCenter">
                <textarea className ="createPost__textarea"
                rows ="3"
                placeholder="Enter Caption Here"
                value ={caption}
                onChange = {(e) => setCaption(e.target.value)}    >            
                </textarea>

                <div className="createPost__imagePreview">
                  <img id="image-preview" alt="" />
                </div>
            </div>
           
            <div className="createPost__loggedInBottom">
            <div class ="createPost__imageUpload">
            <label htmlFor ="fileInput"><AddAPhotoIcon style = {{cursor:"pointer",fontSize :"20px"}}/>
            </label>
            <input id ="fileInput" 
            type ="file"
             accept ="image/*"
              onChange ={handleChange}/>
            </div>
            <button className = "createPost__uploadBtn" 
            onclick ={handleUpload} 
            style = {{color : caption ? "#000" : "lightgrey"}}>
                {`Upload ${progress !=0 ? progress: ""}`}
                </button>
            </div>
            </div>
            ) : (
                <div> 
                    <SignInBtn/>
                        <p style ={{marginLeft : "12px"}}> To post and Comment</p>
                </div> 
            )}

           
        </div>
    );
}

问题出在这一行

db.collection("posts").add

  

我是否遗漏了什么?

现在的问题是我正在尝试制作 Instagram 的克隆,但问题是所有的东西都运行良好,但下面一行出现了问题,它给出了一个错误

未处理的拒绝 (FirebaseError):调用函数 addDoc() 无效数据。不支持的字段值:未定义(在字段中找到 文档帖子中的 profileUrl/K5KaPhmXmT2nCHmFZb2i)

enter image description here

谢谢

解决方法

您上传的文档有两个 photoUrl 字段。

其中一个使用 user.photoUrl 设置,它始终为 undefined,因为 Firebase User 对象的正确属性名称是 photoURL(注意大写字母)。也有可能此属性尚未设置为图像,因此您应该确保在尝试存储它之前检查该属性。