为了更熟悉 API、CRUD 和 React,我在尝试制作一个待办事项应用程序时,在执行一个函数后重新加载组件时遇到了一个小障碍。
案例如下:
- 显示任务
- 用户可以按下按钮将任务标记为已完成
- 任务被标记为完成(这已经在工作)
- 按钮更改为“标记为未完成”(这不会触发)
目前我使用 window.location.reload()
强制每个组件在按下“标记完成”按钮后更新,但是我知道刷新整个页面是相当不必要的,据我所知,使用 javascript 和 React 的全部原因都无效。
因此,我应该使用 this.setState()
来执行此操作,但没有任何解释为什么它不起作用。 this.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: []
它将更新,但会删除整个任务数组。提示我它 - 确实 - 发挥应有的作用。
最佳答案
您正在使用 axios.put
运行异步函数,因此您的 update: true
在 axios.put
返回 promise 之前执行,你可能想在成功时执行 .then(//set the state here)。
所以,沿着这条线:
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
成功,状态将被更新并且您的页面应该重新呈现。
关于javascript - ReactJS:执行函数后重新加载组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48096727/