javascript - 如何使用 React 发送 POST 并刷新页面?

标签 javascript html reactjs

我编写了一个简单的表单,它将包含数据的 POST 请求发送到服务器。单击提交按钮后,我想清除表单,因此我创建了一个刷新页面的函数。该函数工作正常,但现在数据未发送到服务器。

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() 移动到 then block 中的 submitHandler 中,如下所示:

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 - 如何使用 React 发送 POST 并刷新页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72676747/

相关文章:

javascript - 如何更改跨度元素上的所有空格

javascript - 在 React 函数中运行 setInterval() 会发生多次,并且随着时间的推移数量会迅速增加

javascript - 你可以将其作为参数传递给 React 中的无渲染组件吗?

reactjs - 尝试从 componentWillMount 中异步调用的返回值设置状态时,未定义文档

javascript - 使用模板文字通过 javascript 将值分配给 title 属性

html - Firefox 40.0.3 (Windows) 无法使用字体系列

javascript - Handsontable 未加载动态创建的列标题

html - 如何将最小宽度和最大宽度与包装器结合起来?

javascript - typescript 中的绑定(bind)函数和 this

javascript - 如何在动态加载的内容中加载JS?