[英]React - Form submit + set state
in my to do list I'm having issues with the edit method. 在我的待办事项清单中,我在编辑方法方面遇到问题。
I have a form with an input and submit button, when you first submit the form everything works fine, however when you try to do it the second time it appears to refresh the page despite having preventDefault on the method. 我有一个带有输入和提交按钮的表单,当您第一次提交表单时,一切正常,但是,尽管您在方法上设置了preventDefault,但是当您第二次尝试执行此操作时,它似乎仍刷新页面。
I tried removing the defaultValue but that didn't work. 我尝试删除defaultValue,但是没有用。
Edit method 编辑方式
editedData(e) {
e.preventDefault();
let editedValue = this.editedData.value;
let objectKey = this.props.data.key;
let userId = firebase.auth().currentUser.uid;
let dbRef = firebase.database().ref(`users/${userId}/notes/${objectKey}`);
dbRef.update({
value: editedValue
})
this.setState({
editing: false
})
}
Form 形成
if(this.state.editing) {
editingTemplate = (
<form onSubmit={this.editedData}>
<input className="form-input" type="text" defaultValue={this.props.data.value} ref={ref => this.editedData = ref} />
<input type="submit" value="Save" />
</form>
);
}
You are using this.editedData
as method and ref object variable so it will overwrite function to object reference. 您正在使用
this.editedData
作为方法和ref对象变量,因此它将函数覆盖为对象引用。 Here I have changed this.editedData1
now you can get the data. 在这里,我更改了
this.editedData1
现在您可以获取数据了。 Try this let me know if you have any issues. 试试这个让我知道是否有任何问题。
if(this.state.editing) {
editingTemplate = (
<form onSubmit={this.editedData}>
<input className="form-input" type="text" defaultValue={this.props.data.value} ref={ref => this.editedData1 = ref} />
<input type="submit" value="Save" />
</form>
);
}
editedData = (e) => {
e.preventDefault();
let editedValue = this.editedData1.value;
let objectKey = this.props.data.key;
let userId = firebase.auth().currentUser.uid;
let dbRef = firebase.database().ref(`users/${userId}/notes/${objectKey}`);
dbRef.update({
value: editedValue
})
this.setState({
editing: false
})
}
The function is never actually called because it's not bound to the component. 该函数从未真正调用过,因为它没有绑定到组件。 Since the function is being called on the form submit event, the
this
context is not your component. 由于在表单提交事件上调用了该函数,因此
this
上下文不是您的组件。 You have two options. 您有两个选择。 If you have ES7 class properties enabled, you can do the following:
如果启用了ES7类属性,则可以执行以下操作:
editedData = (e) => {
e.preventDefault();
let editedValue = this.editedData.value;
let objectKey = this.props.data.key;
let userId = firebase.auth().currentUser.uid;
let dbRef = firebase.database().ref(`users/${userId}/notes/${objectKey}`);
dbRef.update({
value: editedValue
})
this.setState({
editing: false
})
}
Which binds the this
context to the component. 结合在
this
背景下的组件。
Otherwise you can bind it in the constructor: 否则,您可以将其绑定到构造函数中:
constructor() {
super();
this.editedData = this.editedData.bind(this)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.