reactjs - 如何使用 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 输入,但我正在测试名称输入。
解决方案
“this”在 handleSubmit 函数中未定义。就像杰斯说的,你必须在构造函数中绑定函数。
constructor(props) {
super(props);
this.state = {
name: "",
textarea: "",
};
this.handleSubmit = this.handleSubmit.bind(this);
}
推荐阅读
- spring-boot - Spring boot 2.5.3 和 Spring Cloud Gateway 2020.0.3 间歇性不处理请求
- python - 在 Jupyter 中,为什么有时在 print(end="\r") 之后会有新行
- php - Laravel Http::post : 我(真的)发送“错误请求”吗?
- python - 在python中裁剪图像
- javascript - 节点 js:我在 forEach 循环中推送值时得到空数组
- python - int.to_bytes 返回错误值
- css - 在悬停时淡入背景元素时淡出一个元素
- sql - 将 Excel 公式转换为 SQL Oracle
- java - 远程获取 StartApp Id
- html - 如何在 Bootstrap5 中制作带有列的移动菜单?