React:使用Firebase存储上传图像

时间:2020-08-21 11:02:17

标签: javascript reactjs firebase firebase-storage

我正在写一种上传图片并显示它的方法。

问题是:为什么未在状态下(使用setState)发送图像链接

const storageRef = firebase.storage()

所以这是我的状态:

        this.state = {
        article: {
            title: '',
            content: '',
            createDate : new Date(),
            featureImage: '',
            isPublish: false,
            lastModified: new Date(),
            createUserID: ''
        }

回调函数:

    uploadImageCallBack = (e) => {
    return new Promise(async(resolve, reject) => {
        const file = e.target.files[0]
        const fileName = uuidv4() //uuidv4 generates a random filename
        storageRef.ref().child('Articles/' + fileName).put(file)
            .then(async snapshot => {
                const downloadURL = await storageRef.ref().child('Articles/' + fileName).getDownloadURL()
                resolve({
                    success: true,
                    data: {link: ''}
                })
            })
    })
}

渲染:

<FormGroup>
   <Label className={classes.Label}>Feature image</Label>
      <Input type="file" accept="image/*" className={classes.ImageUploader} onChange={async (e) => {
        const uploadState = await this.uploadImageCallBack(e)
        if(uploadState.success) {
            this.setState({
                hasFeatureImage: true,
                article: {
                    ...this.state.article,
                    featureImage: uploadState.data.link
                }
            })
            console.log(uploadState.data.link)
        }
    }}
>
</Input>

    {
        this.state.hasFeatureImage?
            <img src={this.state.article.featureImage} /> :''
    }

0 个答案:

没有答案