在这一部分,用户可以对帖子发表评论。在服务器端检查并收到数据后,我尝试更改 this.state.comments
值。这样就完成了。但问题是,它并没有改变组件的评论部分。
我已经阅读了之前关于重新渲染的问题,所以请不要标记为重复。下面是代码:
$.post("requests.php", {
requestKey: 'newComment',
commenterUser: commenterUser,
commenterEmail: commenterEmail,
theComment: theComment,
pnum: pnum}, function(data, status, xhr){
if(status == 'success'){
if(data == 'commented'){
this.setState({
comments: data
})
}else{
}
}
});
接收到的数据
是与帖子相关的所有评论,评论部分是显示所有评论的地方。
最佳答案
您也可以使用箭头函数来代替手动绑定(bind)。
this.setState 不工作,因为当您使用正常功能时它有范围问题。
改成箭头函数。检查下面的代码
$.post("requests.php", {
requestKey: 'newComment',
commenterUser: commenterUser,
commenterEmail: commenterEmail,
theComment: theComment,
pnum: pnum}, (data, status, xhr) => {
if(status == 'success'){
if(data == 'commented'){
this.setState({
comments: data
})
}else{
}
}
});
编辑:
如果你想远离作用域问题,你可以使用箭头函数。当你使用箭头函数时,你不需要在构造函数中手动绑定(bind)你的函数
submitComment = () => {
}
如果您使用普通函数并在该函数内使用状态或 Prop ,那么您需要手动将当前对象引用到局部变量,如下所示
let that = this;
that.setState({
name: “update”
});
如有错字请见谅。我用手机回答
关于javascript - 在ajax调用后 react 组件状态变化但不重新渲染组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52018613/