我试图在Redux中进行同步分派调用,在这里,第一个调用更新一个isLoading状态,这样我们就可以在UI上显示一个加载图标,然后第二个调用在幕后执行大量同步计算来更新项目位置--大约需要2-5秒。
第一个操作发生,状态被正确更改,但在发生之后,它似乎没有击中react前端组件,而是进入了第二个调度。当我在第一次分发之后添加一个简短的timeout时,它可以工作,但我不喜欢硬编码固定的等待时间。
这个问题是否有更好的解决办法?
不起作用:
const showLoadingIcon = () => ({type: types.SHOW_LOADING_ICON});
export const updateInteractionTypeScores = (updatedValues) => dispatch => {
dispatch(showLoadingIcon());
dispatch({type: types.UPDATE_VALUES, updatedValues});
};工作:
const showLoadingIcon = () => ({type: types.SHOW_LOADING_ICON});
export const updateInteractionTypeScores = (updatedValues) => dispatch => {
dispatch(showLoadingIcon());
setTimeout(() => dispatch({type: types.UPDATE_VALUES, updatedValues}), 100);
};发布于 2017-09-29 21:19:40
您所称的同步操作实际上是一个异步操作,在特定时间对存储进行更新。这类事情的一般模式是(至少)为操作的每个状态分配三个调度。
启动异步操作会发出一个"ASYNC_ACTION_LAUNCHED“操作,该操作更新存储区,将组件正确连接到存储区(对吗?)因此,将显示加载图标。
成功后,发出一个"ASYNC_ACTION_SUCCESS“,更新存储,使用新存储内容的组件重定向器。
一旦失败,将分派一个"ASYNC_ACTION_FAILURE“,更新存储,使用空内容的组件重建器和错误消息。
实际上,这相当于更多的代码,但这允许了更多的可能性:
const asyncActionLaunched = () => ({type: types.ASYNC_ACTION_STARTED});
const asyncActionSuccess = () => ({type: types.ASYNC_ACTION_SUCCESS});
const asyncActionFailed = () => ({type: types.ASYNC_ACTION_FAILED});
export const updateInteractionTypes = dispatch => {
dispatch(asyncActionLaunched());
// I don't know your setup
// But this whould either be a Promise, or return a boolean
// in the case of a synchronous function
const result = makeSynchronousCalculations();
if (result) {
dispatch(asyncActionSuccess());
// dispatch another action that updates store
} else {
dispatch(asyncActionFailed());
// dispatch another action that updates store
}
// in the case of a promise
asyncBlockingAction()
.then(
dispatch(asyncActionSuccess());
// dispatch another action that updates store
).catch(
dispatch(asyncActionFailed());
// dispatch another action that updates store
);
};https://stackoverflow.com/questions/46494147
复制相似问题