繁体   English   中英

React提交表单不发送POST请求

[英]React Submit Form Not Sending POST Request

我正在尝试为Spring Boot应用程序创建前端,我选择了React,但是我对React或JavaScript没有太多经验。 因此,我有一个要用于发送帖子请求的表单,但是当我按下“提交”按钮时,似乎什么也没发生。 我假设这是我的onSubmit处理程序,但是我不知道这有什么问题。 当我手动发送POST请求时,它工作正常,因此我认为不是REST API引起了问题。

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import { Link } from 'react-router-dom';

class Create extends Component {

  constructor() {
    super();
    this.state = {
      name: '',
      email: '',
      title: '',
      description: ''
    };
  }
  onChange = (e) => {
    const state = this.state
    state[e.target.name] = e.target.value;
    this.setState(state);
  }

  onSubmit = (e) => {
    e.preventDefault();

    const { name, email, title, description } = this.state;

   axios.post('/create', { name, email, title, description })
      .then((result) => {
        this.props.history.push("/")
      });


  }

  render() {
    const { name, email, title, description } = this.state;
    return (
      <div class="container">
       <div class="panel panel-default">
         <div class="panel-heading">
            <h3 class="panel-title">
              Send Message
            </h3>
          </div>
          <div class="panel-body">
            <h4><Link to="/"><span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> Message List</Link></h4>
            <form onSubmit={this.onSubmit}>
             <div class="form-group">
               <label for="name">Name:</label>
               <input type="text" class="form-control" name="name" onChange={this.onChange}/>
              </div>
              <div class="form-group">
               <label for="email">Email:</label>
                <input type="text" class="form-control" name="email" onChange={this.onChange}/>
              </div>
              <div class="form-group">
                <label for="title">Title:</label>
                <input type="text" class="form-control" name="title" onChange={this.onChange}/>
          </div>
          <div class="form-group">
            <label for="description">Description:</label>
            <input type="text" class="form-control" name="description" onChange={this.onChange}/>
          </div>
          <button type="submit" class="btn btn-default">Submit</button>
        </form>
          </div>
       </div>
      </div>
    );
      }
    }

export default Create;

React的第一条规则是,您不直接更新state属性(否则React不会知道状态已更改)。

要告诉您React的表现并不容易。
因此,与其直接设置状态值,不如

onChange = (e) => {
    const state = this.state
    state[e.target.name] = e.target.value;
    this.setState(state);
}

像这样更改它,然后尝试再次提交。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM