在axios POST请求后更新状态

时间:2018-10-08 15:55:00

标签: javascript reactjs axios

我对React很陌生,我已经在后端(Express)上创建了一个CRUD,我想将其绑定到React前端。我有一个允许添加用户的表单,我希望在成功添加用户后更新状态。我通过实现“ document.createElement”并在5秒钟后(使用setTimeout)刷新页面来使其得以启动并运行。我在考虑POST成功后如何重新渲染组件(更新状态)。

这是我到目前为止所管理的:

class App extends Component {
  constructor() {
    super();
    this.state = {
      users: null
    };
  }

  componentDidMount() {
    axios
      .get("http://localhost:3000/customer_all")
      .then(res => {
        console.log(res);
        this.setState({ users: res.data });
      })
      .then(() => console.log(this.state.users.map(item => item.name)))
      .catch(err => console.log(err));
  }

  submit(e) {
    e.preventDefault();
    var form = document.forms[0];
    var data = {};
    var para = document.createElement("p");
    para.textContent = "Success";
    var id = document.getElementById("message");

    data.name = form.name.value;
    data.email = form.email.value;
    axios
      .post("http://localhost:3000/customer", {
        name: data.name,
        email: data.email,
        headers: {
          "Content-Type": "application/json"
        }
      })
      .then(response => {
        id.appendChild(para);
        setTimeout(() => window.location.reload(), 5000);
        form.reset();
      })
      .catch(err => console.log(err));
  }

  render() {
    return (
      <div>
        <div id="message" />
        <form method="POST" onSubmit={this.submit}>
          <label htmlFor="name">Nume </label>
          <input type="text" name="name" /> <br />
          <br />
          <label htmlFor="email">Email </label>
          <input type="email" name="email" required />
          <input type="submit" value="Adauga" />
        </form>
        <ol>
          {!this.state.users
            ? "loading"
            : this.state.users.map((item, i) => <li key={i}>{item.name}</li>)}
        </ol>
      </div>
    );
  }
}

在此先感谢您的提示!

1 个答案:

答案 0 :(得分:1)

在Submit方法中,将新用户添加到数组和setState中。

submit = (e) => {
e.preventDefault();
var form = document.forms[0];
var data = {};
var para = document.createElement("p");
para.textContent = "Success";
var id = document.getElementById("message");

data.name = form.name.value;
data.email = form.email.value;
axios
  .post("http://localhost:3000/customer", {
    name: data.name,
    email: data.email,
    headers: {
      "Content-Type": "application/json"
    }
  })
  .then(response => {
    const {users} = this.state;
    users.push(response.data);
    id.appendChild(para);
    this.setState({users});
    form.reset();
  })
  .catch(err => console.log(err));

}