我有一个表单,用户可以在其中向数据库添加操作以及编辑该操作。我可以在Firebase数据库中看到新数据(和编辑后的数据)。但是,当我刷新我的React应用程序时,它将删除用户存储在数据库中的所有内容。
我已阅读有关保存数据的firebase文档。我读过的大多数地方似乎都是在将硬数据“设置”到数据库中。我需要用户数据的地方。
const updatedActions = [];
database.ref('actions').on('value', (snapshot) => {
console.log(typeof snapshot, '<-- snapshot type')
snapshot.forEach((childSnapShot) => {
updatedActions.push({
key: childSnapShot.key,
...childSnapShot.val()
})
})
})
console.log(updatedActions, '<-- updatedActions')
this.props.fetchingAction(updatedActions)
}
submitAddActions = (e) => {
e.preventDefault();
console.log( this.state.addAction, '<-- new actions')
const newAction = database.ref('actions').push({
action: this.state.addAction
})
console.log(newAction.key, '<-- newAction')
this.setState({
actionKey: newAction.key
}, () => {
console.log(this.state, '<-- this is the full state')
})
}
handleChange = (e) => {
this.setState({
addAction: e.target.value
}, () => {
console.log(this.state.addAction, 'added action in state')
})
}
actionAdd = (e) => {
e.preventDefault();
this.setState({
actionAdd: !this.state.actionAdd
})
}
triggerEditForm = (e) => {
e.preventDefault()
this.setState({
canEditAction: false
})
}
handleEdit = (e) => {
this.setState({
editedAction: e.target.value
})
}
submitEditAction = (e) => {
e.preventDefault();
console.log( this.state.editedAction, '<-- edited action in db')
database.ref('actions/' + this.state.actionKey).update({
action: this.state.editedAction
})
}
render(){
return(
<div>
{this.state.actionAdd ?
<button className="addAction" onClick={this.actionAdd}>Add Action</button>
:
<form onSubmit={this.submitAddActions} id="addActions">
<input type="text" placeholder="Add an action" name="addAction" onChange={this.handleChange}/>
<button className="addAction" type="submit">Add Action</button>
</form>
}
{this.state.canEditAction ?
<button className="addAction" onClick={this.triggerEditForm}>Edit Action</button>
:
<form onSubmit={this.submitEditAction}>
<input type="text" onChange={this.handleEdit} value={this.state.editedAction} />
<button type="submit" className="addAction">Submit</button>
</form>
}
</div>
)
}
}
预期结果只是我可以在刷新React应用程序时看到,当前正在从Firebase实时数据库中删除数据。