Uncaught TypeError: Невозможно прочитать свойство 'balance' из неопределенного - PullRequest
0 голосов
/ 26 января 2019

У меня есть 5 объектов состояния, функция onSubmit предназначена для отправки формы с 5 обновленными объектами состояния. Метод onChange обрабатывает новое состояние и отображает страницу списка клиентов.

Ниже приведен класс, который вызывает ошибку при попытке отправить форму с пятью обновленными состояниями. Мой проект подключен к пожарному депо, я не смог выяснить, почему объект баланса не определен.

В конечном итоге onSubmit должен добавить нового клиента на страницу списка клиентов и создать нового клиента в базе данных firestore.

Может кто-нибудь помочь мне с этой проблемой, это моя первая публикация в stackoverflow?

Снимок экрана

import React, { Component } from "react";
import { Link } from "react-router-dom";
import { compose } from "redux";
import { connect } from "react-redux";
import { firestoreConnect } from "react-redux-firebase";
import PropTypes from "prop-types";

class AddClients extends Component {
  constructor(props) {
    super(props);
    this.state = {
      firstName: "",
      lastName: "",
      email: "",
      phone: "",
      balance: ""
    };
    //if not using arrow functions bind the method in constructor(initialising it)
    this.onChange = this.onChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onChange(e) {
    this.setState({
      [e.target.name]: e.target.value
    });
  }

  onSubmit(e) {
    e.preventDefault();
    //const {firstName,lastName,email,phone,balance} = this.state;
    const { newClient } = this.state;
    const { firestore, history } = this.props;

    if (newClient.balance === "") {
      newClient.balance = 0;
    }
    firestore
      .add({ collection: "clients" }, newClient)
      .then(() => history.push("/"));
  }
  render() {
    // const { firstName, lastName, email, phone, balance } = this.state;
    // console.log(firstName, lastName, email, phone, balance);
    const { disableBalanceOnAdd } = this.props.settings;
    return (
      <div>
        <div className="row">
          <div className="col-md-6">
            <Link to="/" className="btn btn-link">
              <i className="fas fa-arrow-circle-left" /> Back To Dashboard
            </Link>
          </div>
        </div>
        <div className="card">
          <div className="card-header">Add Client</div>
          <div className="card-body">
            <form onSubmit={this.onSubmit}>
              <div className="form-group">
                <label htmlFor="firstName">First Name</label>
                <input
                  type="text"
                  className="form-control"
                  name="firstName"
                  minLength="2"
                  required={true}
                  onChange={this.onChange}
                  value={this.state.firstName}
                />
              </div>
              <div className="form-group">
                <label htmlFor="lastName">Last Name</label>
                <input
                  type="text"
                  className="form-control"
                  name="lastName"
                  minLength="2"
                  required={true}
                  onChange={this.onChange}
                  value={this.state.lastName}
                />
              </div>
              <div className="form-group">
                <label htmlFor="email">Email</label>
                <input
                  type="email"
                  className="form-control"
                  name="email"
                  onChange={this.onChange}
                  value={this.state.email}
                />
              </div>
              <div className="form-group">
                <label htmlFor="phone">Phone</label>
                <input
                  type="text"
                  className="form-control"
                  name="phone"
                  minLength="10"
                  required={true}
                  onChange={this.onChange}
                  value={this.state.phone}
                />
              </div>
              <div className="form-group">
                <label htmlFor="balance">Balance</label>
                <input
                  type="text"
                  className="form-control"
                  name="balance"
                  minLength="1"
                  required={true}
                  onChange={this.onChange}
                  value={this.state.balance}
                  disabled={disableBalanceOnAdd}
                />
              </div>
              <input
                type="submit"
                value="Submit"
                className="btn btn-primary btn-block"
              />
            </form>
          </div>
        </div>
      </div>
    );
  }
}

AddClients.propTypes = {
  firestore: PropTypes.object.isRequired,
  settings: PropTypes.object.isRequired
};
export default compose(
  firestoreConnect(),
  connect((state, props) => ({
    settings: state.settings
  }))
)(AddClients);

1 Ответ

0 голосов
/ 30 января 2019

Я думаю, что вы делаете что-то не так здесь.Внутри функции onSubmit в строке

      const { newClient } = this.state;

Вы должны назначить ее как

      const newClient = Object.assign({}, this.state);

. Это создаст копию объекта this.state и назначит ее для const newClient.Затем вы можете получить доступ к его свойствам как newClient.balance.

...