我有一个异步操作
function fetch(url) {
dispatch => {
request(url).then(
resp => dispatch({type: FETCH_SUCCESS, resp}),
error => dispatch({type: FETCH_FALUIRE, error})
);
}}
UI上有一个列出所有项目的页面,当单击其中一个项目时,它会分派带有该项目URL的操作。
当我先单击item1时,如果item2的响应早于item1,则我会快速单击item2。存储区中item2的数据将被item1覆盖。
fetch('http://remote/items/item1'); //first
fetch('http://remote/items/item2'); // then
如何忽略item1的结果?或如何使项目的派发总是在item1之后触发
我能想到的是,在发送请求之前调度url。
function fetch(url) {
dispatch => {
dispatch({type: FETCH_START, url});
request(url).then(
resp => dispatch({type: FETCH_SUCCESS, resp, url}),
error => dispatch({type: FETCH_FALUIRE, error, url})
);
}
}
在化简器中,我检查URL以确定是否应该忽略响应。
function reduceFetch(state = initialState, action) {
switch(action.type) {
case FETCH_START:
return {initialState, action.url};
case FETCH_SUCCESS:
if (state.uri === action.url) {
return {state, resp: action.resp};
} else {
return state;
}
...
}
}
谢谢你的帮助!
您的解决方案应该可以工作。如果您忽略诸如此类的疯狂行为,那就不为所动
另外,您可以使fetch
函数仅在最近一次调用时调度事件。
const fetchLatest = (called => url => {
const snapshot = ++called
return dispatch => request(url).then(
resp => snapshot === called && dispatch(...),
error => snapshot === called && dispatch(...)
)
})(0)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句