我正在尝试建立一个网站,用户可以在该网站上评论给定帖子。我想在按下按钮时显示评论。一切正常,但是当我单击评论时,它给出了一个错误:-TypeError:_this3未定义。 在这个平台上相当新。请帮忙。
render() {
return (
<div className="container">
{this.state.queries.map(function(item, key) {
return(
<div key={key}>
<hr/>
<div className="list-group-item list-group-item-secondary row">
{item.name}
<div>
{item.description}
</div>
<hr/>
<div>
<button className="btn btn-info" data-toggle="collapse" data-target="#demo"onClick={()=>{
return(
fetch('/queries/'+item._id).
then((Response)=>Response.json()).
then(data =>{
//console.log("comment is:",data.comments);
this.setState({comment:data.comments});
})
)
}}>
Comment
</button>
<div id="demo" className="collapse">
<br/>
<form className="commentForm" action={"http://localhost:5000/queries/"+item._id} method="POST">
<input type="text" className="form-control" placeholder="comment..." name="comment"/>
<button className="btn btn-lg btn-primary btn-block" >Post</button>
</form>
<div>
</div>
</div>
</div>
</div>
</div>
)
})}
</div>
);
}
服务器上json
{
"comments": [
{
"_id": "5b5eadeeb415381598bdc825",
"text": "sfsdfsd",
"__v": 0
},
{
"_id": "5b5ecbe5b415381598bdc827",
"text": "hii from alex",
"__v": 0
},
{
"_id": "5b5ecd9ed8f72736c830a311",
"text": "asdad",
"__v": 0
}
],
"_id": "5b5ea97f7fb6e02d58b80dba",
"name": "ram@gmail.com",
"description": "Is axios still in use?",
"__v": 3
}
答案 0 :(得分:0)
最好为此创建一个新方法,然后将其分配给onClick方法。我认为您不需要为此返回声明
const addComment = () => {
fetch('/queries/'+item._id).
then((Response)=>Response.json()).
then(data => {
//console.log("comment is:",data.comments);
this.setState({comment:data.comments});
})}
... //then use it like this
<button className="btn btn-info" data-toggle="collapse" data-target="#demo" onClick={this.addComment}
答案 1 :(得分:0)
问题是您正在使用正常功能来更改此设置。 请改用箭头功能解决此问题。
this.state.queries.map(function(item, key) { ... }
到
this.state.queries.map((item, key) => { ... }