Ошибка «Не удается прочитать свойство« значение »из неопределенного» при отправке данных формы в мой API в Reactjs » - PullRequest
0 голосов
/ 12 апреля 2020

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

Это мой родительский компонент:

import React, { Component } from "react";
import StepOne from "views/StepOne";
import StepTwo from "views/StepTwo";
import StepThree from "views/StepThree";
import axios from "axios";
import "views/Typography.css";

class Help extends Component {
  constructor(props) {
    super(props)
    this._next = this._next.bind(this)
    this._prev = this._prev.bind(this)
    // Set the initial input values
    this.state = {
      currentStep: 1, // Default is Step 1
      productName: "",
      productPrice: "",
      productCategory: "",
      productBrand: "",
      countryOfOrigin: "",
      riskType: "",
      alertSubmittedBy: "",
      yourCity: "",
      yourAddress: "",
      productImage: undefined,
      description: "",
      showMessage: false,

      pname: "",
      price: 0,
      pCategory: "",
      pBrand: "",
      pCountryOfOrigin: "",
    }
    // Bind the submission to handleChange()
    this.handleChange = this.handleChange.bind(this);
    this.handleChange1 = this.handleChange1.bind(this);
    this.handleChange2 = this.handleChange2.bind(this);
    this.handleChange3 = this.handleChange3.bind(this);
    this.onChangeHandlerPost = this.onChangeHandlerPost.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  //---------------------on change of file-------------------
  handleChange(event) {
    this.setState({ countryOfOrigin: event.target.value });
    console.log(this.state.countryOfOrigin);
  }
  handleChange1(event) {
    this.setState({ riskType: event.target.value });
    console.log(this.state.riskType);
  }
  handleChange2(event) {
    this.setState({ alertSubmittedBy: event.target.value });
    console.log(this.state.alertSubmittedBy);
  }
  handleChange3(event) {
    this.setState({ productCategory: event.target.value });
    console.log(this.state.productCategory);
  }
  //-------------------------------------------------------
  onChangeHandlerPost = (event) => {
    this.setState({
      productImage: event.target.files[0],
    });
    console.log(event.target.files[0]);
  };

  onClickHandler = (event) => {
    console.log("Clicked");

    this.setState({
      showMessage: true,
    });
  };
  //----------------------------handle Submit----------------
  handleSubmit = (event) => {
    event.preventDefault();
    const form = new FormData();
    form.append("productName", this.productName.value);
    form.append("productPrice", this.productPrice.value);
    form.append("productCategory", this.productCategory.value);
    form.append("productBrand", this.productBrand.value);
    form.append("countryOfOrigin", this.state.countryOfOrigin);
    form.append("riskType", this.state.riskType);
    form.append("alertSubmittedBy", this.state.alertSubmittedBy);
    form.append("yourCity", this.yourCity.value);
    form.append("yourAddress", this.yourAddress.value);
    form.append("productImage", this.state.productImage);
    form.append("description", this.textArea.value);
    axios.post("https://alert-amigo-api.herokuapp.com/products", form, {
      headers: { "Content-Type": "multipart/form-data" },
    });

    this.setState({ showMessage: true });

    console.log("Clicked");
    //---------------------------------------------------
    /* const pname = this.productName.value;
    const price = this.productPrice.value;
    const pCategory = this.productCategory.value;
    const pBrand = this.productBrand.value;
    const pCountryOfOrigin = this.state.countryOfOrigin;

    this.props.createProduct(pname, price, pCategory, pBrand, pCountryOfOrigin); */
  };

  _next() {
    let currentStep = this.state.currentStep
    // If the current step is 1 or 2, then add one on "next" button click
    currentStep = currentStep >= 2? 3: currentStep + 1
    this.setState({
      currentStep: currentStep
    })
  }

  _prev() {
    let currentStep = this.state.currentStep
    // If the current step is 2 or 3, then subtract one on "previous" button click
    currentStep = currentStep <= 1? 1: currentStep - 1
    this.setState({
      currentStep: currentStep
    })
  }

  // Use the submitted data to set the state
  // handleChange(event) {
  //   const {name, value} = event.target
  //   this.setState({
  //     [name]: value
  //   })
  // }

  get previousButton(){
  let currentStep = this.state.currentStep;
  // If the current step is not 1, then render the "previous" button
  if(currentStep !==1){
    return (
      <button
        className="btn btn-secondary"
        type="button" onClick={this._prev}>
      Previous
      </button>
    )
  }
  // ...else return nothing
  return null;
}

get nextButton(){
  let currentStep = this.state.currentStep;
  // If the current step is not 3, then render the "next" button
  if(currentStep <3){
    return (
      <button
        className="btn btn-primary float-right"
        type="button" onClick={this._next}>
      Next
      </button>
    )
  }
  // ...else render nothing
  return null;
}
  // Render UI will go here...
  render() {
return (
  <React.Fragment>
  <div>
    <div className="alert-1">
      <h3 className="a">
        Report a Product <i className="pe-7s-news-paper"></i>
      </h3>
      <hr className="new1"></hr>
      <p className="k">
        Please check if the product you want to report has already been
        reported earlier using the <b>"Search"</b> option.
      </p>
      <p className="k">
        {" "}
        If you couldn't find the product there, then you can <b>
          "Report"
        </b>{" "}
        the product here.
      </p>
      <p className="k">
        {" "}
        Please ensure to fill in all the required details and ensure that
        the details entered by you are correct.
      </p>
    </div>
    <br />
    <br />
    <div className="container1">
  <p>Step {this.state.currentStep} </p>

  <form onSubmit={this.handleSubmit}
        id="myForm"
        method="POST"
        encType="multipart/form-data">
    <StepOne
      currentStep={this.state.currentStep}
      onChange={this.handleChangePost}
      onChange={this.handleChange3}
      productName={this.state.productName}
      productPrice={this.state.productPrice}
      productCategory={this.state.productCategory}
      productBrand={this.state.productBrand}
      handleChange={this.handleChange}
    />
    <StepTwo
      currentStep={this.state.currentStep}
      handleChange={this.handleChange}
      onChange={this.handleChange1}
      onChange={this.handleChange2}
    />
    <StepThree
      currentStep={this.state.currentStep}
      handleChange={this.handleChange}
      onChange={this.handleChangePost}
      onChange={this.onChangeHandlerPost}
    />
    {this.previousButton}
    {this.nextButton}
  </form>
  <br />

  <div>
    {this.state.showMessage && (
      <div className="alert alert-success">
        <strong>Success!</strong> successful submitted a report
      </div>
    )}
  </div>
</div>
</div>
  </React.Fragment>

)
}
}
export default Help

Это мои дочерние компоненты: я хочу знать, как использовать реквизиты для отправки данных поля в родительский компонент

import React, { Component } from "react";
class StepOne extends React.Component {
  render() {
    if (this.props.currentStep !== 1) { // Prop: The current step
      return null
    }
    // The markup for the Step 1 UI
    return(
      <div className="form-group">
        <label> Product Name: </label>
        <input
          className="form-control"
          id="productName"
          type="text"
          ref={(input) => {
            this.productName = input;
          }}
          placeholder="Product Name"
          required
          // Prop: The email input data
          onChange={this.props.handleChangePost} // Prop: Puts data into state
        />
        <label> Product Price: </label>
        <input
          id="productPrice"
          type="text"
          ref={(input) => {
            this.productPrice = input;
          }}
          onChange={this.props.handleChangePost}

          className="form-control"
          placeholder="Product Price in Euros (€)"
          required
        />
        <label>
         Product Category:
          <select
            id="productCategory"
            value={this.productCategory}
            onChange={this.handleChange3}
            required
          >
            <option value="Toys">Toys</option>
            <option value="Motor vehicles">Motor vehicles</option>
            <option value="Clothing, textiles and fashion items">Clothing, textiles and fashion items</option>
            <option value="Electrical appliances and equipment">Electrical appliances and equipment</option>
            <option value="Childcare articles and children's equipment">Childcare articles and children equipment</option>
            <option value="Cosmetics">Cosmetics</option>
            <option value="Jewellery">Jewellery</option>
            <option value="Other">Other</option>
          </select>
        </label>
        <br/>
        <label> Brand Name: </label>
        <input
          id="productBrand"
          type="text"
          onChange={this.handleChangePost}
          ref={(input) => {
            this.productBrand = input;
          }}
          className="form-control"
          placeholder="Product Brand"
          required
        />
      </div>
    )
  }
}
export default StepOne

import React, { Component } from "react";
class StepTwo extends React.Component {
  render() {
    if (this.props.currentStep !== 2) {
    return null
  }
  return(
    <div className="form-group">
    <label>
      Country of origin:
      <select
        id="countryoforigin"
        value={this.countryoforigin}
        onChange={this.handleChange}
        required
      >
        <option>--select--</option>
        <option value="albania">Albania</option>
        <option value="algeria">Algeria</option>
        <option value="argentina">Argentina</option>
        <option value="austria">Austria</option>
        <option value="bangladesh">Bangladesh</option>
        <option value="barbados">Barbados</option>
        <option value="belarus">Belarus</option>
        <option value="belgium">Belgium</option>
        <option value="bosnia and Herzegovina">
          Bosnia and Herzegovina
        </option>
        <option value="Brazil">Brazil</option>
        <option value="Bulgaria">Bulgaria</option>
        <option value="Combodia">Combodia</option>
        <option value="Cameroon">Cameroon</option>
        <option value="Canada">Canada</option>
        <option value="Chile">Chile</option>
        <option value="china">China</option>
        <option value="Cocos (Keeling) Islands">
          Cocos (Keeling) Islands
        </option>
        <option value=" Colombia"> Colombia</option>

        <option value="Congo">Congo</option>
        <option value=" Croatia"> Croatia</option>
        <option value="Cyprus">Cyprus</option>
        <option value=" Czech Republic"> Czech Republic</option>
        <option value=" Democratic People's Republic of Korea">
          {" "}
          Democratic People's Republic of Korea
        </option>
        <option value="Democratic Republic Of Congo">
          Democratic Republic Of Congo
        </option>
        <option value=" Denmark"> Denmark</option>
        <option value="Dominican Republic">Dominican Republic</option>
        <option value=" Ecuador"> Ecuador</option>
        <option value="Egypt">Egypt</option>
        <option value="Estonia">Estonia</option>
        <option value="Finland">Finland</option>
        <option value="Former Yugoslav Republic of Macedonia">
          Former Yugoslav Republic of Macedonia
        </option>
        <option value="France">France</option>
        <option value="Germany">Germany</option>
        <option value="Greece">Greece</option>
        <option value="Guatemala">Guatemala</option>
        <option value=" Guinea-Bissau"> Guinea-Bissau</option>
        <option value="Hong Kong">Hong Kong</option>
        <option value="Hungary">Hungary</option>
        <option value="Iceland">Iceland</option>
        <option value="India">India</option>
        <option value="Indonesia">Indonesia</option>
        <option value=" Iran"> Iran</option>
        <option value=" Ireland"> Ireland</option>
        <option value="Israel">Israel</option>
        <option value="Italy">Italy</option>
        <option value="Ivory Coast">Ivory Coast</option>
        <option value="Jamaica">Jamaica</option>
        <option value="Japan">Japan</option>
        <option value="Jordan">Jordan</option>
        <option value=" Lao People's Democratic Republic">
          {" "}
          Lao People's Democratic Republic
        </option>
        <option value=" Latvia"> Latvia</option>
        <option value="Lebanon">Lebanon</option>
        <option value="Lithuania">Lithuania</option>
        <option value="Luxembourg">Luxembourg</option>
        <option value="Madagascar">Madagascar</option>
        <option value="Malaysia">Malaysia</option>
        <option value=" Mali"> Mali</option>
        <option value="Malta">Malta</option>
        <option value="Mexico">Mexico</option>
        <option value="Monaco">Monaco</option>
        <option value="Morocco">Morocco</option>
        <option value=" Mozambique"> Mozambique</option>
        <option value=" Namibia"> Namibia</option>
        <option value="Nepal">Nepal</option>
        <option value="New Zealand">New Zealand</option>
        <option value=" Nicaragua"> Nicaragua</option>
        <option value="Nigeria">Nigeria</option>
        <option value="Norway">Norway</option>
        <option value="Pakistan">Pakistan</option>
        <option value="Paraguay">Paraguay</option>
        <option value="People's Republic of China">
          People's Republic of China
        </option>
        <option value="Peru">Peru</option>
        <option value="Philippines">Philippines</option>
        <option value="Poland">Poland</option>
        <option value="Portugal">Portugal</option>
        <option value="Republic of Korea">Republic of Korea</option>
        <option value="Republic of Moldova">
          Republic of Moldova
        </option>
        <option value="Romania">Romania</option>
        <option value="Russia">Russia</option>
        <option value="Russian Federation">Russian Federation</option>
        <option value="Saudi Arabia">Saudi Arabia</option>
        <option value="Senegal">Senegal</option>
        <option value="Serbia">Serbia</option>
        <option value="Singapore">Singapore</option>
        <option value="Slovakia">Slovakia</option>
        <option value="Slovenia">Slovenia</option>
        <option value="South Africa">South Africa</option>
        <option value="South Korea">South Korea</option>
        <option value="Spain">Spain</option>
        <option value="Sri Lanka">Sri Lanka</option>
        <option value="Sweden">Sweden</option>
        <option value="Switzerland">Switzerland</option>
        <option value="Syria">Syria</option>
        <option value="Taiwan">Taiwan</option>
        <option value="Thailand">Thailand</option>
        <option value="The Bahamas">The Bahamas</option>
        <option value="The Netherlands">The Netherlands</option>

        <option value="Togo">Togo</option>
        <option value="Tunisia">Tunisia</option>
        <option value="Turkey">Turkey</option>

        <option value="Ukraine">Ukraine</option>
        <option value="United Arab Emirates">
          United Arab Emirates
        </option>
        <option value="United Kingdom">United Kingdom</option>
        <option value="United States">United States</option>
        <option value="Uruguay">Uruguay</option>
        <option value="Vietnam">Vietnam</option>
      </select>
    </label>
    <label>
      Risk Type or Level:
      <select
        id="risktype"
        value={this.risktype}
        onChange={this.handleChange1}
        required
      >
        <option>--select--</option>
        <option value="very low">very low</option>
        <option value="low">low</option>
        <option value="medium">medium</option>
        <option value="High">High</option>
      </select>
    </label>
    <label>
      Alert Submitted by:
      <select
        id="alertsubmittedby"
        value={this.alertsubmittedby}
        onChange={this.handleChange2}
        required
      >
        <option>--select--</option>
        <option value="consumer">Consumer</option>
        <option value="producer">Producer</option>
        <option value="supplier">Supplier</option>
        <option value="eu Authorities">Eu Authorities</option>
      </select>
    </label>
    </div>
  );
  }
}
export default StepTwo

import React, { Component } from "react";
class StepThree extends React.Component {
  render() {
    if (this.props.currentStep !== 3) {
    return null
  }
  return(
    <React.Fragment>
    <div className="form-group">
      <label>Notifiers data</label>
      <input
        id="yourCity"
        type="text"
        onChange={this.handleChangePost}
        ref={(input) => {
          this.yourCity = input;
        }}
        className="form-control"
        placeholder="Your city"
        required
      />
      <label>Address</label>
      <input
        id="yourAddress"
        type="text"
        onChange={this.handleChangePost}
        ref={(input) => {
          this.yourAddress = input;
        }}
        className="form-control"
        placeholder="Your Address"
        required
      />
      <label> Upload Images: </label>
      <input
        name="uploadFile"
        type="file"
        onChange={this.onChangeHandlerPost}
        ref={(input) => {
          this.uploadFile = input;
        }}
        className="form-control"
        placeholder="upload Images"
        required
      />
      <label> Description </label>
      <textarea
        name="textArea"
        onChange={this.handleChangePost}
        ref={(input) => {
          this.textArea = input;
        }}
        className="form-control"
        placeholder="Write here.."
        required
        col="5"
        row="15"
      />
    </div>
    <br />
    <button type="submit" className="mt-auto btn btn-primary" id="new2">Submit</button>
    </React.Fragment>
  );
  }
}
export default StepThree

1 Ответ

0 голосов
/ 12 апреля 2020

Реагирует на архитектуру, основанную на однонаправленном потоке данных. Это означает, что данные передаются только от родителя к потомку. Вы можете использовать сторонние библиотеки, такие как Redux, или использовать новейшую функцию React, которая называется ContextAPI.

...