Reactjs 0.14.0,Vanilla Flux
异步操作依赖是一个持续的概念斗争。我已经看了几个月(死得很严重),而且每个类似的线程都没有说清楚我认为是React / Flux学习曲线中最难的部分之一。
问题:
如果你希望在ActionA完成后直接进行一次ActionB,那么根据Flux模式建议将视图更新的地方并不是很明显(因为可能是ActionA) - > ActionB链接是反模式的
注意:也许componentDidUpdate可以做到最好,但这意味着可以不必要地多次调用ActionB。
我正在尝试做什么
所以我使用the common ActionA->WebAPI->Action->Dispatcher->Stores->View->ActionB
在大多数情况下,这样的流程如下:
ActionA-> WebAPI->动作(异步) - > Dispatcher->商店 - >查看 - > ActionB
通常情况是,ActionB依赖于ActionA的Payload数据在它的商店中准备就绪。(waitFor()不是为这样的异步情况而设计的。)
示例:
Main.js
componentWillMount: function(){
AuthActionCreators.checkForSession((loggedIn) => { //THIS IS A CALLBACK TO DO AN ACTION DEPENDENT ON USER DATA BEING IN THE USERSTORE
if(loggedIn){
AnotherActionCreators.updateAnotherStoreNowUserStuffIsInStores(this.props.someProp);//Action->Action(supposedly an anti-pattern)
}
});
},
AuthActionCreators.js
//Problem #1 Pointless Middle-Men Actions When Using The Pattern: ActionToServer->WebAPIUtils->ActionWithPayload
//Note: Many say to not call WebAPIUtils directly in Components
checkForSession: function(callback){
/* Notice how this action SEEMED to not need the dispatcher
because its a call to a server and I wait for a return to call an Action
that can actually dispatch a payload)*/
WebAPIUtils.hasSession(callback);
},
WebAPIUtils.js
//Problem #2 Async Actions calling dependent Actions
//ActionA -> ActionB is supposedly an anti pattern instead of :ActionA -> Dispatcher -> Store -> View -> ActionB
var hasSession = function(callbackDepOnUserData) {
let jwt = localStorage.getItem('jwt');
if (jwt) {
$.ajax(this.href, {
success: function(userData) {
ServerActionCreators.receiveUserPayloadInStore(userData);//Async Action that will actually sends a payload(I'm kinda okay with this action)
callbackDepOnUserData(true);//This callback(which is an action)feels like an anti-pattern but it the only way to call after dependent data is
//available in store
},
});
}
else{
console.log("does not have a session");
}
}