我正在使用 React with Flux。
我的组件中有一个函数,可以在单击时调用执行操作:
onClickEventEdit: function(itemId) {
ScheduleActions.getEventById(itemId) // this ultimately is set into `currentEventById` state
var title = this.state.currentEventById['title'] || ""
console.log(title) // logs nothing
console.log(this.state.currentEventById) //logs empty object {}
// then show modal
$('#eventSelectedModal').modal({
show: true
});
},
我的ScheduleAction
是一个ajax调用来检索事件信息。当 Ajax 操作完成后,它会更新我的商店。我的印象是,它会在标题分配和日志发生后更新我的商店。
调用操作后如何访问此信息,以便立即向客户端显示该信息?
最佳答案
AJAX 调用(从技术上讲 XMLHttpRequests )是异步执行的。这意味着,当 HTTP 调用仍在等待响应时,您的同步代码将继续运行。这会产生您所期望的行为。
最简单的解决方案是使用异步调用完成时调用的回调参数来扩展 getEventById()
方法。您现在可以将调用后应执行的代码移至回调中,从而有效地延迟其执行;
onClickEventEdit: function(itemId) {
ScheduleActions.getEventById(itemId, function() {
var title = this.state.currentEventById['title'] || ""
console.log(title) // logs nothing
console.log(this.state.currentEventById) //logs empty object {}
// then show modal
$('#eventSelectedModal').modal({
show: true
});
});
},
要获得更干净的解决方案,您可以查看 Promises .
关于javascript - Reactjs:立即使用更新的状态数据(来自商店),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38359037/