【发布时间】:2018-02-10 12:23:24
【问题描述】:
所以过去几周我一直在学习 React,现在我正在尝试使用 Firebase。
现在,我正在尝试使编辑和删除博客文章成为可能。在过去的几周里,我用 express、rails 等做了一些类似的事情,所以我认为我已经很好地处理了它,所以现在我正在尝试比较并了解它们之间的差异。
大部分功能都已轻松重构以配合我现在正在做的工作,所以我不确定如何调整这个功能以在这里工作,或者它是否根本不起作用,然后转向如何我在这里做得好吗。
我上次尝试编辑的原始代码是:
getInitialState(){
return {editable: false}
},
handleEdit(){
if( this.state.editable){
var title = this.refs.title.value;
var article= this.refs.article.value;
var id = this.props.post.id;
var post = {id: id, title: title, article: article};
this.props.handleUpdate(post);
}
this.setState({editable: !this.state.editable})
},
render: function(){
var title= this.state.editable? <input className= "form-control" type='text' ref='title' defaultValue={this.props.post.title}/>:
<h3>{this.props.post.title}</h3>;
var article= this.state.editable ? <input className= "form-control" type='text' ref='article' name="logEntryEdit" defaultValue={this.props.post.article}/>:
<p className="postText">{this.props.post.article}</p>;
return(
<div >
<div className="text-center postTitle">
{title}
</div>
<hr/>
<br/>
<div className="text-center" id="postText">
{article}
</div>
<br/>
<hr/>
<button className="btn btn-danger delete-button" onClick={this.props.handleDelete}>Delete</button>
<button className="btn btn-primary" onClick={this.handleEdit}>{this.state.editable ? 'Submit' : 'Edit'}</button>
</div>
)
当然,我编辑了项目名称等。我如何设置我的编辑页面是首先通过 firebase 生成的 id 将所选帖子传递到单个视图页面中,然后将其传递到编辑页面中。删除也应该来自该视图页面。
这是我尝试在上述函数中添加的编辑:
constructor(props){
super(props);
this.state = {
title: '',
body: '',
post:{},
};
}
componentDidMount(){
database.ref(`posts/${this.props.match.params.postId}`)
.on('value', snapshot => {
this.setState({post: snapshot.val()});
});
this.postId= this.props.match.params.postId;
}
//edit function goes here
render() {
return (
<div className="container">
<form onSubmit={this.onHandleUpdate}>
<div className="form-group">
<input value={this.state.post && this.state.post.title} className="form-control" type="text" name="title" ref="title" placeholder="Title" onChange={this.onInputChange}/>
</div>
<br/>
<div className="form-group">
<input value={this.state.post && this.state.post.body} className="form-control" type="text" name="body" ref="body" placeholder="Body" onChange={this.onInputChange}/>
<br/>
</div>
<button className="btn btn-success">Submit</button>
</form>
</div>
);
}
当我尝试添加它时,我也得到了一个
组件正在更改要控制的文本类型的不受控制的输入。输入元素不应从不受控切换到受控(反之亦然)。在组件的生命周期内决定使用受控或不受控的输入元素
它将我链接到我浏览过的文档。
能否请您告诉我如何制作适合我的原始代码并在这段时间内工作,或者应该如何完成,以便我可以比较和理解其中的差异?
【问题讨论】:
标签: javascript reactjs firebase react-router