【问题标题】:Sending data from React form to Firebase database将数据从 React 表单发送到 Firebase 数据库
【发布时间】:2017-09-19 18:33:50
【问题描述】:

我正在使用 React 处理表单,并希望将收集到的数据发送到 Firebase 数据库。但是,我不完全确定如何有效地进行设置。我已经在下面发布了一些我目前拥有的代码的 sn-ps。

这是我的组件的开始。据我了解,componentDidMount 正在将数据从json 文件中提取到这些字段中。但我不确定我是否应该在此处输入代码以发送到 Firebase。

class FormContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      firstName: '',
      lastName: '',
      email: '',
      startDate: moment(),
      courseName: '',
      courseCity: '',
      courseStateOptions: [],
      courseStateSelection: '',
      holeNumberOptions: [],
      holeNumberSelection: '',
      yardage: '',
      clubOptions: [],
      clubSelection: ''
    };
    this.handleFormSubmit = this.handleFormSubmit.bind(this);
    this.handleClearForm = this.handleClearForm.bind(this);
    this.handleFirstNameChange = this.handleFirstNameChange.bind(this);
    this.handleLastNameChange = this.handleLastNameChange.bind(this);
    this.handleEmailChange = this.handleEmailChange.bind(this);
    this.handleDateChange = this.handleDateChange.bind(this);
    this.handleCourseNameChange = this.handleCourseNameChange.bind(this);
    this.handleCourseCityChange = this.handleCourseCityChange.bind(this);
    this.handleCourseStateSelect = this.handleCourseStateSelect.bind(this);
    this.handleHoleNumberSelect = this.handleHoleNumberSelect.bind(this);
    this.handleYardageChange = this.handleYardageChange.bind(this);
    this.handleClubSelect = this.handleClubSelect.bind(this);
  }
  componentDidMount() {
    fetch('./nhior_db.json')
      .then(res => res.json())
      .then(data => {
        this.setState({
          firstName: data.firstName,
          lastName: data.lastName,
          email: data.email,
          date: data.date,
          courseName: data.courseName,
          courseCity: data.courseCity,
          courseStateOptions: data.courseStateOptions,
          courseStateSelection: data.courseStateSelection,
          holeNumberOptions: data.holeNumberOptions,
          holeNumberSelection: data.holeNumberSelection,
          yardage: data.yardage,
          clubOptions: data.clubOptions,
          clubSelection: data.clubSelection
        });
      });
  }

在下面我有我所有的handleFirstNameChange() 函数等。我不会在这里全部发布,但这里有一些供参考。

  handleCourseNameChange(e) {
    this.setState({ courseName: e.target.value }, () => console.log('course name:', this.state.courseName));
  }
  handleCourseCityChange(e) {
    this.setState({ courseCity: e.target.value }, () => console.log('course city:', this.state.courseCity));
  }
  handleCourseStateSelect(e) {
    this.setState({ courseStateSelection: e.target.value}, () => console.log('course state', this.state.courseStateSelection));
  }
  handleHoleNumberSelect(e) {
    this.setState({ holeNumberSelection: e.target.value}, () => console.log('hole number', this.state.holeNumberSelection));

然后我有我的handleClearForm()handleFormSubmit()

  handleFormSubmit(e) {
    e.preventDefault();

    const formPayload = {
      firstName: this.state.firstName,
      lastName: this.state.lastName,
      email: this.state.email,
      date: this.state.date,
      courseName: this.state.courseName,
      courseCity: this.state.courseCity,
      courseStateSelection: this.state.courseStateSelection,
      holeNumberSelection: this.state.holeNumberSelection,
      yardage: this.state.yardage,
      clubSelection: this.state.clubSelection
    };

    alert('Thanks for the submission!');
    // console.log('Send this in a POST request:', formPayload)
    this.handleClearForm(e);
  }

最后,render 方法包含所有输入,这里有一些。

  render() {
    return (
      <form className="container" onSubmit={this.handleFormSubmit}>
        <h6>If you are one of the SPECIAL FEW to make a hole in one, you have the opportunity to record your success in the national registry!
          Please enter your information, the date of your Hole-In One and click Continue.</h6>
          <SingleInput
            inputType={'text'}
            title={'First name'}
            name={'name'}
            controlFunc={this.handleFirstNameChange}
            content={this.state.firstName}
            placeholder={'First Name'} />
          <SingleInput
            inputType={'text'}
            title={'Last name'}
            name={'name'}
            controlFunc={this.handleLastNameChange}
            content={this.state.lastName}
            placeholder={'Last Name'} />
          <SingleInput
            inputType={'text'}
            title={'Email'}
            name={'name'}
            controlFunc={this.handleEmailChange}
            content={this.state.email}
            placeholder={'Email'} />
          <DatePicker
            selected={this.state.startDate}
            onChange={this.handleDateChange}/>

我只需要知道是否有更好更有效的方式将收集到的数据发送到 Firebase。

【问题讨论】:

    标签: forms reactjs firebase firebase-realtime-database


    【解决方案1】:

    如果我理解正确,你问的是两个问题:

    • 我应该在哪里输入要发送到 Firebase 的代码,并且
    • 如何有效地进行设置。

    答案取决于您所说的“高效”。

    为了简单地让您的示例正常工作,您将 firebase 调用添加到 handleFormSubmit 中,就在您的 console.log 所在的位置。但你可能知道。

    那么什么是有效的?如果您想以一种可管理的方式组织您的代码,那么一个好的开始是一个像MobXRedux 这样的状态框架。将大部分状态(即从 firebase 获得的数据)保存在一个地方是个好主意。

    我使用react-redux,基本上将我的逻辑分为两种控制器。一个控制器(通常称为异步函数或 thunk)处理您的数据库获取/保存,而另一个控制器为视图准备(映射)您的数据和事件处理程序。这样我很少使用this.setState(...)this.state 并获得清晰的、可单元测试的关注点分离。

    在您的示例中,您将在 handleFormSubmitdispatch 一个异步操作(在 redux 术语中),并让此操作将数据推送到 firebase 并在全局状态 store 中反映更改(例如保存状态)。然后,您只需使用从 store 传递到 props 的数据来渲染您的组件。

    【讨论】:

      猜你喜欢
      • 2017-08-06
      • 1970-01-01
      • 2017-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-02
      • 1970-01-01
      • 2014-01-20
      相关资源
      最近更新 更多