我有以下提交新帖子的组件。表格使用materiail-ui。我可以成功改变状态。但是当我提交表单时,它给了我一个错误,即{state is empty}错误。但是在渲染事件中,我试图控制日志状态,每当我键入新值时,我都可以看到状态正在改变。下面是代码示例。对于完整代码,您可以在我的github中查看https://github.com/HtunHtunHtet/reactProject2/blob/master/client/src/components/add_post.js。提前致谢。
class AddPost extends Component {
state = {
postCategory: "react",
postTitle: "",
postAuthor: "",
postContent: ""
};
handleChange = (event, index, postCategory) => this.setState({postCategory});
handleSubmit(e){
e.preventDefault();
console.log(this.state);
const data = {
timestamp: Date.now(),
title: this.state.postTitle,
body: this.state.postContent,
author: this.state.postAuthor,
category: this.state.postCategory,
deleted: false,
voteScore: 1
};
this.props.fetchAddPost(data);
this.props.history.push("/");
}
handleInputChange = e => {
const target = e.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
};
答案 0 :(得分:1)
make handleSubmit a arrow function或者将它绑定到构造函数中的组件“this”。在handleSubmit中使用“this”时,执行上述任一操作将确保“this”引用您的Component。