将表单数据上传到Firebase时遇到问题

时间:2020-09-26 10:11:31

标签: javascript reactjs firebase google-cloud-firestore

我做了一个反应形式,使变量中的输入值失效。我已经检查过,错误不是值本身,而是纯粹在上传过程中。请帮忙。我没有收到任何错误,只是没有用。我已经将所有必要的firebase数据存储在firebase.js中。

import React, { Component} from 'react';
import logo from './logo.svg';
import {Link, BrowserRouter as Router, Switch, Redirect} from 'react-dom';
import App from './App';
import './profile.css'
import firebase from './firebase'

class Profile extends Component{

    state = {
        name: "",
        age: "",
    }

    handleInput = event => {
        this.setState({[event.target.name] : event.target.value});
    }
    uploadValues = event => {
        firebase
            .firestore()
            .collection('user1')
            .add({
                name: this.state.name,
                age: this.state.age,
            });
            alert('Data uploaded');
    }
    logValues = () => {
        alert(this.state.name);
        alert(this.state.age);
        this.uploadValues();
    }
    render(){
        return(
            <div className="container">
                <h1>Update your Profile here</h1>
                <form className="profileForm">
                    <input type = "text" id="nameInput" placeholder="Full Name" onChange = 
{this.handleInput} name = "name"/>
                    <input type = "number" id="birthdate" placeholder="Age" onChange = 
{this.handleInput} name = "age" />
                    <button type = "submit" onClick={this.logValues} id="saveChanges" >Save 
Changes</button>
                </form>
            </div>
        );
    }
}
export default Profile;

1 个答案:

答案 0 :(得分:2)

add函数返回一个Promise,因此该进程本身未在执行。

将您的函数转换为异步函数,或向返回的Prom添加then()

uploadValues = async () => {
    await firebase
        .firestore()
        .collection('user1')
        .add({
            name: this.state.name,
            age: this.state.age,
        });
    alert('Data uploaded');
}

执行您的承诺:

uploadValues = () => {
    firebase
        .firestore()
        .collection('user1')
        .add({
            name: this.state.name,
            age: this.state.age,
        }).then(() => {
            alert('Data uploaded');
        }).catch((err) => alert(err);
}