无法将Firebase上载的图像url发送到react挂钩中的另一个组件中

问题描述 投票:0回答:1

我无法使用react挂钩将Firebase存储中的上传图片网址发送到另一个组件中,有人可以帮我吗?我是新手,大约2个星期就在这部分代码上工作,并且没有任何进展,这确实让我很烦。

这是图像URL应当呈现的主要组成部分

import React, { useState, useEffect} from "react";
import firebase from "firebase";
import Uploader from "./uploader";

function EditorBlog() {
    const [title, setTitle] = useState("");
    const [text, setText] = useState("");
    const [category, setCategory] = useState("");
    const [url , setUrl]= useState("");
    const [items, setItems] = useState([]);

    const onSubmit = (data) => {

        data.preventDefault();
        setItems([...items, {title, text, category , url} ]);
        firebase
            .firestore()
            .collection('blogContent')
            .add({
                title,
                category,
                text,
                url
                // file
            })
            .then(()=>{
                setTitle('')
                setCategory('')
                setText('')
                setUrl('')
            });
    };


    return (
        <div>

            <form onSubmit={onSubmit} className="col-md-6 mx-auto mt-5">
                <div className="form-group">
                    <label htmlFor="Title">Blog Title</label>
                    <input
                        type="text"
                        name="title"
                        value={title}
                        onChange={(e) => setTitle(e.target.value)}
                        className="form-control"
                        id="Title"
                        placeholder="Arnold Schwarzneiger"
                    />
                </div>
                <Uploader/>
                <div className="form-group">
                    <label htmlFor="categorySelect">Select Category</label>
                    <select className="form-control" value={category} onChange={e => setCategory(e.target.value)} name="category" id="categorySelect">
                        <option>Nutrition</option>
                        <option>Fitness</option>
                        <option>Recipes</option>
                        <option>Succesfull Stories</option>
                        <option>Other</option>
                    </select>
                </div>
                <div className="form-group">
                    <label htmlFor="blogText">Blog Text</label>
                    <textarea
                        className="form-control"
                        name="text"
                        id="blogText"
                        rows="3"
                        value={text}
                        onChange={(e) => setText(e.target.value)}
                    ></textarea>
                </div>
                <button
                    type="submit"
                    className="btn btn-primary offset-5"
                    onClick={onSubmit}
                >
                    Save
                </button>
            </form>

            <div className="mt-5">
                {
                    items.map((item, index) => (
                        <div className="row bg-dark mx-auto ">
                        <div key={item.id} className="col-md-6 blogs_content mx-auto mt-5 " >
                            <div className="mblog_imgtop "><p>Beginner</p></div>
                            <img className="img-fluid editor_img " src={item.url} alt=""/>
                            <div className="col-md-12 rblog_txt text-center mx-auto">
                                <h6 className="mblog_category mx-auto m-4">{item.category}</h6>
                                <h2 className="blogs_title col-md-10 mx-auto">{item.title}</h2>
                                <div className="mt-5 mblog_innertxt col-md-11 mx-auto">{item.text}</div>
                                <div className="readm mt-5"><i>READ MORE</i></div>
                            </div>

                        </div>
                        </div>
                    ))
                }
            </div>
        </div>
    );
}
export default EditorBlog;

这是我的第二个组件,必须将上载的图像URL发送到主要组件中

import React, {useState} from "react";
import {storage} from "../../firebaseConfig";
import firebase from "firebase";


export default function Uploader() {
    const [image , setImage]= useState(null);
    const [url , setURL]= useState("");
    const [imgURL, setImgURL] = useState('');
    const [progress , setProgress]= useState(0);
    const [error , setError]= useState("");


    const handleChange =e =>{
    const file = e.target.files[0];

    if (file){
        const fileType= file["type"];
        const validFileType= ["image/gif", "image/png", "image/jpg", "image/jpeg"];
        if (validFileType.includes(fileType)){
            setError("");
            setImage(file);
        }else setError("Siz rasm kiritmadingiz");
    }else {
        setError("Iltimos faylni tanlang");
    }
    };


    const handleUpload = props=>{

        if (image){
            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 =>{
                    setError(error);
                },
                ()=>{
                    storage.ref("images").child(image.name).getDownloadURL().then(url=>{
                        setURL(url);
                        console.log(url);
                        firebase
                            .firestore()
                            .collection('images')
                            .add({
                                url
                            })
                            .then(()=>{
                                setURL('')
                            });

                        setProgress(0);
                    });


                }
            )

        }else setError("Xatolik Iltimos rasmni yuklang")
    };
    return(
        <div>
            <form >
                <div className="form-group" >
                    <input type="file" className="form-control" onChange={handleChange} />
                    <button type="button" className="btn btn-primary btn-block" onClick={handleUpload}>Upload</button>
                </div>
            </form >
            <div>
                {progress > 0 ? <progress style={{marginLeft: "15px"}} value={progress} max="100"/> :""}
            </div>
            <div style={{height : "100px", marginLeft: "15px", fontWeight: "600"}}>
                <p style={{color: "red"}}>{error}</p>
            </div>
            <img src={url || 'http://via.placeholder.com/400x300'} alt="Uploaded images" height="300" width="650"/>
        </div>
    )
}
reactjs firebase react-hooks firebase-storage
1个回答
0
投票

使用回调,您的EditorBlog组件可以告诉Uploader组件上载完成后要做什么。

换句话说,EditorBlog将名为“ onComplete”的函数作为对上载器的支持。上载完成后,上载器以URL作为参数调用此函数。

EditorBlog

const [url , setUrl]= useState("");

const handleCompletedUpload = (url) => {
  setUrl(url);
}

return (
  // ...
  <Uploader onComplete={handleCompletedUpload} />
  // ...
);

上载者:

export default function Uploader({ onComplete }) {

// ...

  uploadTask.on(
    "state_changed", (snapshot) => { .. },
    (error) => { ... },
    () => {
      // Success. Get the URL and call the prop onComplete
      uploadTask.snapshot.ref.getDownloadURL().then(url => {
        onComplete(url); // Call the callback provided as a prop
      });
    })

// ...
};
© www.soinside.com 2019 - 2024. All rights reserved.