2016-12-15 58 views
0

我在理解异步调用的概念时遇到了问题。如何在状态更新后调用异步函数?

我的状态:sentence: { author: '', context: '', date: '' }

然后,我有,在终极版更新的状态的功能:

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

这些更新方法是不同的行动,并有不同的减速。

中更新的状态属性之后,我想这将数据发送到服务器:

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

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

+0

你应该做的是周围的其他方法,第一次上传了一句到服务器,然后响应是否成功的决心,承诺和更新状态。 现在,如果您只更新reducer,而没有使用updateAuthor和updateDate向服务器发出请求,则不必在上传前等待reducer。 – jmac

+0

实际上,我的状态比这个大得多,内部对象我有不同的数据数组,并且在上传之前,到服务器上,我需要读取一些其他属性,比如id和一些这些数组,然后将它块大小,导致服务器拥有每个组块的不同URL。 –

+0

您可以使用生命周期方法:* componentWillReceiveProps()*。每次连接的减速器都会更新,您将获得有关新道具的信息。 – jmac

回答

1

一种方法是利用componentDidUpdatecomponentWillReceiveProps生命周期方法来检查新的道具是否有你想做的改变,然后从那里做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() 
} 
+0

是的,谢谢这是一个更好的方法来更新receiveProps。我曾尝试过,但在比较道具和nextProps时犯了错误。 –

1

事情让这两个更新在相同的功能,并通过回调此功能:在updateAuthorAndDate

edit(author, date) { 
    const { sentence, updateAuthorAndDate } = this.props 
    updateAuthorAndDate(sentence, author, date, this.uploadToServer) 
} 

然后,就在打电话的时候更新完成回调:

updateAuthorAndDate(sentence, author, date, uploadToServer) { 
    // update the author 
    // update the date 
    // then call the callback when the updates are done: 
    uploadToServer() 
} 

如果您使用setState(如果使用Redux,则可能不适用),请小心。 setState是异步的,所以你需要调用回调函数的第二个参数:

this.setState({ ... }, /* called when the update is done */ uploadToServer) 
+0

你好,非常感谢你的帮助,实际上我是用componentWillReciveProps来做的,这让生活更轻松 –