首页 > 解决方案 > 为什么我尝试提交表单时没有做任何事情?

问题描述

我正在尝试创建一个要提交表单的网站。然而,即使我现在有一个http://formspree.io/可以转发给我,并且当我有时转发给我:

            <form action="http://formspree.io/myaddress@gmail.com" method="post">
                <label for="Name">Name</label><br/>
                <input type="text" name="Name"/><br/>
                <label for="emailAddress">E-Mail address</label><br/>
                <input type="text" name="emailAddress"/><br/>
                <textarea id="subject" name="subject" placeholder="Write something.."></textarea><br/>
                <input type="submit" name="SUBMIT"/>
            </form>

我决定制作 React 组件来创建一个有状态的模型来提交表单。但是,当我点击提交按钮时,它什么也不做,而且我也不知道如何让它改变页面上的内容。我的代码是:

 handleFormSubmit(e) {
    e.preventDefault();
    let userData = this.state.newUser;

    fetch('http://formspree.io/myAddress@gmail.com', {
      method: "POST",
      body: JSON.stringify(userData),
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      }
    }).then(response => {
      response.json().then(data => {
        console.log("Successful" + data);
      });
    });
  }

我的导入和构造函数是:

import Input from "./FormComponents/Input";
import TextArea from "./FormComponents/TextArea";
import Select from "./FormComponents/Select";
import Button from "./FormComponents/Button";

class FormContainer extends Component {
  constructor(props) {
    super(props);

    this.state = {
      newUser: {
        name: "",
        email: "",
        location: "",
        message: ""
      },

      locationOptions: ['(outside the USA', 'AL', 'AK', 'AS', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FM', 'FL', 'GA', 'GU', 'HI', 
      'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MH', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 
      'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'MP', 'OH', 'OK', 'OR', 'PW', 'PA', 'PR', 'RI', 'SC', 'SD', 'TN', 'TX', 
      'UT', 'VT', 'VI', 'VA', 'WA', 'WV', 'WI', 'WY' ]


    };
    this.handleTextArea = this.handleTextArea.bind(this);
    this.handleFullName = this.handleFullName.bind(this);
    this.handleEmailAddress = this.handleEmailAddress.bind(this);
    this.handleFormSubmit = this.handleFormSubmit.bind(this);
    this.handleClearForm = this.handleClearForm.bind(this);
    this.handleInput = this.handleInput.bind(this);
  }

为什么点击提交按钮时什么也没有发生?

标签: javascriptreactjs

解决方案


handleFormSubmit(e) {
    e.preventDefault();
    let userData = this.state.newUser;

    fetch('http://formspree.io/myAddress@gmail.com', {
      method: "POST",
      body: JSON.stringify(userData),
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      }
    }).then(response => {
      response.json().then(data => {
        console.log("Successful" + data);
      });
    }).catch(error => {
        console.log('post error', error);
     });
  }

您应该能够看到问题所在。


推荐阅读