Javascript ReactJS:在函数执行后重新加载组件?
为了更加熟悉API、CRUD和React,在创建待办应用程序的过程中,我遇到了在执行函数后重新加载组件时的一个小障碍 情况如下:Javascript ReactJS:在函数执行后重新加载组件?,javascript,reactjs,Javascript,Reactjs,为了更加熟悉API、CRUD和React,在创建待办应用程序的过程中,我遇到了在执行函数后重新加载组件时的一个小障碍 情况如下: constructor(){ super(); this.state = { tasks: [], update: false }; this.markFinished = this.markFinished.bind(this); this.update = this.update.bind(this); } markFin
constructor(){
super();
this.state = {
tasks: [],
update: false
};
this.markFinished = this.markFinished.bind(this);
this.update = this.update.bind(this);
}
markFinished(id, title, content){
axios.put('/api/tasks/'+id, querystring.stringify({
task_id: id,
title: title,
content: content,
state: 'finished'
}),{
headers: {"Content-Type": "application/x-www-form-urlencoded"}
})
.catch(function(err){
console.log(err)
})
this.setState({update: true});
}
window.location.reload()
在按下“mark finished”按钮后强制每个组件进行更新,但是我知道在这一点上刷新整个页面是不必要的,而且据我所知,使用javascript和react的全部原因都是无效的
因此,我应该使用this.setState()
来代替它,但如果不解释原因,它就无法工作。这两种方法都不推荐使用此.forceUpdate()
代码如下:
constructor(){
super();
this.state = {
tasks: [],
update: false
};
this.markFinished = this.markFinished.bind(this);
this.update = this.update.bind(this);
}
markFinished(id, title, content){
axios.put('/api/tasks/'+id, querystring.stringify({
task_id: id,
title: title,
content: content,
state: 'finished'
}),{
headers: {"Content-Type": "application/x-www-form-urlencoded"}
})
.catch(function(err){
console.log(err)
})
this.setState({update: true});
}
在setState的这个实现中,我是否缺少一些东西?
奇怪的是,如果我将
update:true
替换为tasks:[]
它会更新,但会删除整个tasks数组。提示我it-does-按应有的方式运行。您正在使用axios.put运行异步函数,因此您的更新:true
在axios.put返回承诺之前执行。如果成功,您可能希望执行一个。然后(//在此处设置状态)
因此,沿着这条路线:
let that = this;
axios.put('/api/tasks/'+id, querystring.stringify({
task_id: id,
title: title,
content: content,
state: 'finished'
}),{
headers: {"Content-Type": "application/x-www-form-urlencoded"}
})
.then(function(success) {
that.setState({update: true})
}
.catch(function(err){
console.log(err)
})
成功运行
axios.put
后,状态将更新,页面应重新呈现 您正在使用axios.put
运行异步函数,因此您的更新:true
在axios.put
返回承诺之前执行。您可能希望执行一个。然后(//在此处设置状态)成功
因此,沿着这条路线:
let that = this;
axios.put('/api/tasks/'+id, querystring.stringify({
task_id: id,
title: title,
content: content,
state: 'finished'
}),{
headers: {"Content-Type": "application/x-www-form-urlencoded"}
})
.then(function(success) {
that.setState({update: true})
}
.catch(function(err){
console.log(err)
})
成功运行axios.put
后,状态将更新,页面应重新呈现 奇怪的是,它返回“this is undefined”,尽管我已经在构造函数中绑定了函数。奇怪的是,它返回“this is undefined”,尽管我已经在构造函数中绑定了函数。