将React表单值保存到firebase实时数据库

时间:2018-02-10 06:59:23

标签: reactjs firebase firebase-realtime-database

我已经完成了这个代码,它在编写console.log()方法时正确地显示了控制台输出,但它并没有将代码存储到我的数据库中。

它没有显示任何其他错误,但不会将数据存储到数据库,因此请告诉我要更改的内容以存储到数据库。

以下是代码:

import React, { Component } from 'react';
    var firebase = require('firebase');
    var uuid = require('uuid');

    var config = {
        apiKey: "AIzaSyDf5i7ULK0JTWYM3_X3wMQPUaaLPRYExC0",
        authDomain: "usurvey-419eb.firebaseapp.com",
        databaseURL: "https://usurvey-419eb.firebaseio.com",
        projectId: "usurvey-419eb",
        storageBucket: "usurvey-419eb.appspot.com",
        messagingSenderId: "395101866940"
      };
      firebase.initializeApp(config);
    class Usurvey extends Component {
      constructor(props)
      {
        super(props);
        this.state={
          uid:uuid.v1(),
          firstName: '',
          lastName:''
        };
        this.submitData=this.submitData.bind(this);
        this.inputData=this.inputData.bind(this);
      }
      submitData()
      {
        document.write({uid: this.state.uid,firstName:this.state.firstName,lastName:this.state.lastName});
        // document.write(this.state.firstName);
        // document.write(this.state.lastName);


        firebase.database().ref('Newdata/'+this.state.uid).set({
          firstName: this.state.firstName,
          lastName: this.state.lastName
        });
      }
      inputData(event)
      {
        var firstName = this.refs.name1.value;
        var lastName = this.refs.name1.value;
        console.log(this.state.uid,this.state.firstName,this.state.lastName);

        this.setState({firstName:firstName, lastName:lastName});
        console.log(this.state.firstName,this.state.lastName);
      }
      render(){
        return(
          <div>
            <form onSubmit={this.submitData}>
              <input type="text" onChange={this.inputData} ref="name1"/>
              <input type="text" onChange={this.inputData} ref="name2"/>
            <input type="submit" />Submit
            </form>
          </div>
        );
      }
    }
    export default Usurvey;

1 个答案:

答案 0 :(得分:1)

提交表单时,您必须阻止默认行为,否则您的页面将刷新。将submit事件作为参数传递给submitData()函数,并阻止默认行为,如此...

submitData(event) {
        event.preventDefault();
        firebase
          .database()
          .ref(`Newdata/${this.state.uid}`)
          .set({
            firstName: this.state.firstName,
            lastName: this.state.lastName,
          })

      }

表单是旧学校的HTML,从单页应用程序之前的几天开始,所以当在一个花哨的新框架中使用它们时,你必须明确告诉它不要自动重新加载页面。它默认重新加载,因为这是Web在单页应用程序出现之前的工作方式。

提供所有代码并从数据库onMount添加控制台日志以显示正在存储和检索数据。复制到编辑器中它应该可以工作。

import React, { Component } from 'react';
const firebase = require('firebase');
const uuid = require('uuid');

const config = {
  apiKey: 'AIzaSyDf5i7ULK0JTWYM3_X3wMQPUaaLPRYExC0',
  authDomain: 'usurvey-419eb.firebaseapp.com',
  databaseURL: 'https://usurvey-419eb.firebaseio.com',
  projectId: 'usurvey-419eb',
  storageBucket: 'usurvey-419eb.appspot.com',
  messagingSenderId: '395101866940',
};
firebase.initializeApp(config);

class Usurvey extends Component {
  constructor(props) {
    super(props);
    this.state = {
      uid: uuid.v1(),
      firstName: '',
      lastName: '',
    };
    this.submitData = this.submitData.bind(this);
    this.inputData = this.inputData.bind(this);
  }

  componentDidMount() {
    firebase
      .database()
      .ref(`Newdata/${this.state.uid}`)
      .on('value', snap => console.log('from db', snap.val()));
  }

  submitData(event) {
    event.preventDefault();
    firebase
      .database()
      .ref(`Newdata/${this.state.uid}`)
      .set({
        firstName: this.state.firstName,
        lastName: this.state.lastName,
      })
      .catch(error => console.log(error));
  }
  inputData(event) {
    const firstName = this.refs.name1.value;
    const lastName = this.refs.name2.value;
    this.setState({ firstName, lastName });
  }
  render() {
    return (
      <div>
        <form onSubmit={this.submitData}>
          <input type="text" onChange={this.inputData} ref="name1" />
          <input type="text" onChange={this.inputData} ref="name2" />
          <input type="submit" />Submit
        </form>
      </div>
    );
  }
}
export default Usurvey;