【发布时间】:2020-11-10 11:07:07
【问题描述】:
我是新手,我想知道为什么我一直收到无法读取“未定义”错误的属性值。当我对 this.state.username 和 this.state.todoList 进行控制台登录时,我可以看到状态正在更新,但只有在我单击提交按钮后才会出现错误。
有什么建议吗?谢谢!
import React, { Component } from "react";
import axios from "axios";
export default class TestNote extends Component {
constructor(props) {
super(props);
this.onChangeUsername = this.onChangeUsername.bind(this);
this.onChangeTodoList = this.onChangeTodoList.bind(this);
this.state = {
username: "",
todoList: "",
};
}
onChangeUsername(e) {
this.setState({
username: e.target.value,
});
console.log(this.state.username);
}
onChangeTodoList(e) {
this.setState({
todoList: e.target.value,
});
}
onSubmit(e) {
e.preventDefault();
const todoList = {
username: this.state.username,
todoList: this.state.todoList,
};
console.log(todoList);
axios
.post("http://localhost:5000/list/add", todoList)
.then((res) => console.log(res.data));
}
render() {
return (
<div className="container">
<form>
<label>Username: </label>
<input
type="text"
required
value={this.state.username}
onChange={this.onChangeUsername}
/>
<label>TodoList: </label>
<input
type="text"
value={this.state.todoList}
onChange={this.onChangeTodoList}
/>
<input type="submit" value="Add This List" onClick={this.onSubmit} />
</form>
</div>
);
}
}
【问题讨论】:
-
您还需要将
this绑定到您的onSubmit处理程序,即this.onSubmit = this.onSubmit.bind(this);或将onSubmit转换为箭头函数以便this绑定自动 . -
除了@DrewReese 提到的,你也可以使用不用每次都绑定的es6。
onSubmit = (e) => {...} -
好的,这似乎有效。谢谢!