我正在delete
输入一个对象,然后立即检索一个可用对象的列表,遇到了一个竞态问题。DELETE
请求受CORS飞行前OPTIONS
请求的约束,而GET
请求则不受约束。这意味着我的计划
DELETE /things/21
GET /things/
变为:
OPTIONS /things/21
GET /things
DELETE /things/21
而GET
的结果包括对象21。
我想避免人为地增加延迟;有没有其他方法可以确保DELETE
先发生?
(The请求是从我的react应用程序的完全不同的组件触发的)
编辑:
我有一个组件Things
,它呈现一个内容的摘要列表,还有一个组件Thing
,它呈现一个细节页面。Thing
包含一个Delete
按钮,该按钮触发删除并导航到Things
。“触发删除”的意思是:触发一个 AJAX DELETE到/things/21
并从我的本地redux存储中删除第21项。Things
有一个componentWillMount
,它触发一个GET
来检索可用内容的列表,当它们到达时,我的redux reducer将它们全部添加到它的存储中。
编辑:示例:
Redux操作创建者
export const deleteThing = thingId => ({
type: 'DELETE_THING',
payload: thingId
});
export const retrieveThings = () => ({
type: 'FETCH_THINGS'
});
负责API请求的“减速器”
export default store => next => action => {
switch (action.type) {
case 'DELETE_THING':
return deleteObj(store.dispatch, action.type, `/things/{action.payload}`, action.payload);
case 'FETCH_THINGS':
return getObj(store.dispatch, action.type, '/things/');
}
}
const getObj = (dispatch, action, url) => {
return sendRequest(dispatch, () => fetch(url)
.then(processResponse(dispatch, action))
.catch(handleError(dispatch, action))
);
};
const deleteObj = (dispatch, action, url, payload) => {
return sendRequest(dispatch, () => fetch(url, {
method: 'DELETE',
headers
})
.then(results => {
if (results.status >= 400) return handleError(dispatch, action)(results);
// DELETE doesn't return anything but reducers want to know what was deleted, so pass the payload
return dispatch({
type: `${action}_SUCCESS`,
payload
});
})
.catch(handleError(dispatch, action))
);
}
// Wraps a fetch request, triggering redux events on send/receive (regardless of outcome)
const sendRequest = (dispatch, fn) => {
dispatch({type: 'SENDING_REQUEST'});
const always = () => dispatch({type: 'RECEIVED_RESPONSE'});
return fn().then(always, always);
}
减速器/存储器为Thing
s
export default (state = initialState, action) => {
case 'DELETE_THING_SUCCESS':
return state.deleteIn(['byId'], action.payload);
}
React组件
class Thing {
render () {
return (
<div>
<h1>{props.thing.id}</h1>
<button onClick={this.props.deleteThing}>Delete</button>
</div>
);
}
deleteThing () {
this.props.triggerActionToSend
// Pretend this is `connect`ed to a redux store
this.props.deleteThing(this.props.id);
// AJAX to delete from server
fetch({
url: '/thing/' + this.props.id,
method: 'delete'
});
// Redirect to main list
this.props.navigate('/things/');
}
}
// Pretend this is a `connect`ed component that receives a `things` prop from a redux store
class Things {
componentWillMount () {
this.props.retrieveThings();
}
render () {
return (
<ul>
{this.props.things.map(x => <li>x.id</li>)}
</ul>
);
}
);
const App = () => (
<div>
<Route path="/things" component={Things} />
<Route path="/thing/:thingId" component={Thing} />
</div>
);
1条答案
按热度按时间ujv3wf0j1#
将导航调用更改为等待
fetch
promise解析。对于从本地存储中删除,可能应该执行相同的操作,但这不是当前的问题