我编写了一个简单的表单,可以向服务器发送包含数据的post请求.单击submit按钮,我想清除表单,所以我创建了一个刷新页面的函数.该函数工作正常,但现在数据不会发送到服务器.

import React, {Component} from "react";
import axios from "axios";

class PostForm extends Component {

constructor(props) {
    super(props);
    this.state = {
        id: '',
        name: '',
        surname: '',
        country: ''
    }
}

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

clearFunc = () => {
    window.location.reload(false);
}

submitHandler = e => {
    e.preventDefault();
    console.log(this.state);
    axios.post('http://localhost:8080/human/add/', this.state)
        .then(response => {
            console.log(response)
        })
        .catch(error => {
            console.log(error)
        });
}


render() {
    const {id, name, surname, country} = this.state;
    return (
        <div>
            <form id="input-form" onSubmit={() => {
                this.submitHandler();
                this.clearFunc()
            }}>
                <div>
                    <input type="number" name="id" value={id} onChange={this.changeHandler}/>
                </div>
                <div>
                    <input type="text" name="name" value={name} onChange={this.changeHandler}/>
                </div>
                <div>
                    <input type="text" name="surname" value={surname} onChange={this.changeHandler}/>
                </div>
                <div>
                    <input type="text" name="country" value={country} onChange={this.changeHandler}/>
                </div>
                <button type="submit">Submit</button>
            </form>
        </div>
    )
}
}

export default PostForm;

推荐答案

我会把这条线this.clearFunc()移到submitHandler里面,then街区,就像这样:

submitHandler = (e) => {
  e.preventDefault();
  console.log(this.state);
  axios
    .post("http://localhost:8080/human/add/", this.state)
    .then((response) => {
      console.log(response);
      this.clearFunc();
    })
    .catch((error) => {
      console.log(error);
    });
};

此外,如果只是清空表单,则无需刷新页面,只需执行以下操作:

clearFunc = () => {
  this.setState({
    id: "",
    name: "",
    surname: "",
    country: "",
  });
};

Javascript相关问答推荐

如何编辑代码FlipDown.js倒计时?

Redux查询多个数据库Api reducerPath&

google docs boldText直到按行执行应用脚本错误

将字符串UTC Date转换为ngx—counting leftTime配置值的数字

切换时排序对象数组,切换不起作用

空的结果抓取网站与Fetch和Cheerio

如何从隐藏/显示中删除其中一个点击?

优化Google Sheet脚本以将下拉菜单和公式添加到多行

我可以使用使用node.js创建的本地主机来存储我网站上提交的所有数据吗?没有SQL或任何数据库.只有HTML语言

如何在Angular拖放组件中同步数组?

让chart.js饼图中的一个切片变厚?

<;img>;标记无法呈现图像

Google脚本数组映射函数横向输出

每次重新呈现时调用useState initialValue函数

OnClick更改Json数组JSX中的图像源

无法设置RazorPay订阅API项目价格

在GraphQL解析器中修改上下文值

JQuery使用选项填充HTMLSELECT并设置默认结果,默认结果显示为空

如何在Firebase中读取对象的特定字段?

如何格式化API的响应