javascript - 如何在状态更新后调用异步函数?

标签 javascript reactjs ecmascript-6 redux

我在理解异步调用的概念时遇到了问题。

我的状态:句子:{作者:'',上下文:'',日期:''}

然后我有一个更新 Redux 中状态的函数:

edit(author, date) {
    let { sentence } = this.props;
    this.props.updateAuthor(sentence, author);
    this.props.updateDate(sentence, date)
}

这些更新方法是不同的操作,并且具有不同的 reducer 。

状态属性更新后,我想通过以下方式将数据发送到服务器:

function uploadToServer() {
    this.props.upload(this.props.sentence);
}

我迷失在更新完成后如何调用上传功能。

最佳答案

一种方法是利用 componentDidUpdatecomponentWillReceiveProps生命周期方法来检查新的 props 是否具有您想要的更改,然后执行 this.props.upload从那里。类似的东西

componentWillReceiveProps (newProps) {
  // check if your state is updated with the attributes
  // this function will get called when it's going to receive new props,
  // in this case, when the redux store gets changed
  // this.props will be the unchanged props, newProps will be the changed props
  // then do this.props.upload()
} 

关于javascript - 如何在状态更新后调用异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41169886/

相关文章:

javascript - 无法在 'requestAnimationFrame' : The callback provided as parameter 1 is not a function. 上执行 'Window'

javascript - Redux - 从状态中删除项目

javascript - 干净的箭头函数 - 对数组中的多个元素调用生成器

javascript - Yarn Workspaces,工作区不会发出错误或警告

node.js - VSCode 调试 (F5) React 应用程序给出 SyntaxError : Unexpected identifier

javascript - ES6 导入定义的执行顺序是什么?

node.js - 如何在 Coffeescript 1.9 上强制使用生成器?

javascript - 火狐浏览器 JavaScript 兼容性

javascript - 获取未匹配到单个数组的数组元素的结果

javascript - jQuery:无法在 Chrome 上运行 $.get (http get)