javascript - ReactJS:执行函数后重新加载组件?

标签 javascript reactjs

为了更熟悉 API、CRUD 和 React,我在尝试制作一个待办事项应用程序时,在执行一个函数后重新加载组件时遇到了一个小障碍。

案例如下:

  1. 显示任务
  2. 用户可以按下按钮将任务标记为已完成
  3. 任务被标记为完成(这已经在工作)
  4. 按钮更改为“标记为未完成”(这不会触发)

目前我使用 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: trueaxios.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/

相关文章:

javascript - 按钮单击触发 anchor 选项卡

java - 使用 Selenium (Java) 与 React 下拉菜单交互 : "other element would receive the click"

javascript - 将数据从 React 传递到 Node Express 服务器

javascript - 使用 Jest 时如何访问外部 javascript 方法/对象?

javascript - PhoneGap 给出 NSURLErrorDomain 错误 -999

javascript - 对象不支持此属性或方法 'isotope'

javascript - ReactJS/JS 保存/导出表单输入

javascript - 在 MVC 路由之上构建一个具有反应的 SPA

javascript - 如果不存在,则将输入值添加到数组

javascript - 如果用户提交新搜索,是否会中断搜索的执行?