首页 > 解决方案 > 如何使用 Axios 以表单的形式发布到数据库?

问题描述

import React from "react";
import axios from "axios";
import { config } from "@fortawesome/fontawesome-svg-core";
import "./AddFolder.css";

export default class AddFolder extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
      textarea: "",
    };
  }

  handleCancelBtn() {
    window.history.back();
  }
  updateName(n) {
    console.log("updateName, ran: " + n + "  type is: " + typeof n);
    this.setState({ name: { value: n } });
  }
  updateTextarea(area) {
    console.log("updateTextarea, ran: " + area);
    this.setState({ textarea: { value: area } });
  }
  handleSubmit(e) {
    e.preventDefault();
    console.log("handleSubmit, ran");
    const { name } = this.state;
    try {
      axios.post(
        `${config.API_ENDPOINT}/folders`,
        {
          name,
        }.then((res) => {
          console.log(res);
          console.log(res.data);
          window.location = "/retrieve"; //This line of code will redirect you once the submission is succeed
        })
      );
      console.log("folder created");
    } catch (e) {
      console.log("there was an error: " + e.message);
    }
  }
  render() {
    return (
      <form className="addfolder-form" onSubmit={(e) => this.handleSubmit(e)}>
        <h2>Add Folder</h2>
        <div className="form-group">
          <label htmlFor="name">name:</label>
          <input
            type="text"
            className="name-input"
            name="name"
            id="name"
            onChange={(e) => this.updateName(e.target.value)}
          />
        </div>
        <div className="form-group">
          <label htmlFor="text-area">content: </label>
          <textarea
            id="text-area"
            name="text-area"
            rows="4"
            cols="50"
            onChange={(e) => this.updateTextarea(e.target.value)}
          />
        </div>
        <div className="button-group">
          <button
            type="reset"
            className="addfolder-btn"
            onClick={this.handleCancelBtn}
          >
            nevermind
          </button>
          <button
            type="submit"
            className="addfolder-btn"
            onClick={this.handleSubmit}
          >
            save
          </button>
        </div>
      </form>
    );
  }
}

在此代码上,const { name } = this.state;我收到以下错误:

TypeError:无法读取未定义的属性“状态”

为什么它未定义,如何将数据发布到存储在 ${config.API_ENDPOINT}/folders` 中的本地存储中?

我正在尝试使用 axios 将表单输入添加到 /folders 端点,到目前为止输入正在工作,但是当我尝试提交它时,我得到了上面的错误。我知道我还没有 textarea 输入,但我正在测试名称输入。

标签: reactjs

解决方案


“this”在 handleSubmit 函数中未定义。就像杰斯说的,你必须在构造函数中绑定函数。

constructor(props) {
  super(props);
  this.state = {
    name: "",
    textarea: "",
  };
  this.handleSubmit = this.handleSubmit.bind(this);
}

推荐阅读