[英]react component state change after ajax call but does not rerender component
在这一部分,用户可以评论帖子。 在服务器端检查并收到数据后,我尝试更改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{
}
}
});
收到的data
是与帖子相关的所有评论,评论部分是显示所有评论的地方。
您也可以使用箭头功能而不是手动绑定。
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{
}
}
});
编辑:
如果您想远离范围问题,可以使用箭头功能。 当您使用箭头功能时,您无需在构造函数中手动绑定您的函数
submitComment = () => {
}
如果您使用普通函数并在该函数内使用状态或道具,则需要手动将当前对象引用到本地变量,如下所示
let that = this;
that.setState({
name: “update”
});
对不起,如果有任何拼写错误。 我在移动电话中回答
let _this = this;
$.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{
}
}
});
我认为这个问题是与你的范围this
,在JavaScript this
总是在词汇方面。
你有一个范围问题。
让我们考虑这个例子:
function foo() {
this.bar = 'lorem';
this.ipsum = function() {
console.log(this.bar);
};
}
如果你打电话ipsum
,它会记录undefined
,因为this
有指ipsum
function
。 让我们考虑这个例子:
function foo() {
this.bar = 'lorem';
var that = this;
this.ipsum = function() {
console.log(that.bar);
};
}
在这种情况下that
存储外部this
,因此如果调用ipsum
将记录'lorem'
。 让我们考虑一个箭头函数的例子:
function foo() {
this.bar = 'lorem';
this.ipsum = () => {
console.log(this.bar);
};
}
在这种情况下,如果你调用ipsum
'lorem'
将被写入控制台。
您也可以使用bind来实现此目的。
让我们使用箭头函数为您的示例:
$.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{
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.