我遇到如下情况,我正在从actionCreators内部调用http调用,如下所示
FetchDataStoreData.js
export const actionCreators = {
deleteUserManagement: (id) => async (dispatch) => {
const url = `api/UserManagement/${id}`;
return await fetch(url, { method: 'DELETE', headers: { 'Content-Type': 'application/json; charset=UTF-8' } });
}
}
从组件文件中,我正在调用redux动作,如下所示
FetchFile.js
handleDeleteClick(id) {
this.props.deleteUserManagement(id);
// Need to call this.ensureDataFetched(); after the delete is successful from the server side
this.ensureDataFetched(); --> This method should call once the delete is successful
}
一切正常,但是我需要调用this.ensureDataFetched();。服务器端响应成功后的方法。
是否也可以使用任何通用方法来创建http调用?
答案 0 :(得分:2)
Onw方法是您可以从操作中返回承诺并在组件中处理它。像这样
FetchDataStoreData.js
export const actionCreators = {
deleteUserManagement: (id) => (dispatch) => {
const url = `api/UserManagement/${id}`;
return fetch(url, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json; charset=UTF-8' }
});
}
}
现在在组件中处理它,然后以
的方式调用sureDataFetched函数。FetchFile.js
handleDeleteClick(id) {
this.props.deleteUserManagement(id).then(res => {
// this will run only deleteUserManagement fetch will complete.
this.ensureDataFetched();
}
}
也许对您有帮助。
答案 1 :(得分:0)
将handleDeleteClick更改为
handleDeleteClick = async (id) => {
await this.props.deleteUserManagement(id);
// Need to call this.ensureDataFetched(); after the delete is successful from the server side
this.ensureDataFetched(); --> This method should call once the delete is successful
}
答案 2 :(得分:0)
为了使用异步功能,您可以将其作为answer above执行,并且有几种方法可以调用 http 。如果您正在寻找component: {
name: 'YourComponent'
}
,
Example.js
XMLHttpRequest API
如果您不是要寻找这个,那么您就是在寻找var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
}
if (request.status === 200) {
console.log('success', request.responseText);
} else {
console.warn('error');
}
};
request.open('GET', 'https://mywebsite.com/endpoint/');
request.send();
。
Example.js
WebSocket
除此之外,可以使用var ws = new WebSocket('ws://host.com/path');
ws.onopen = () => {
// connection opened
ws.send('something'); // send a message
};
ws.onmessage = (e) => {
// a message was received
console.log(e.data);
};
ws.onerror = (e) => {
// an error occurred
console.log(e.message);
};
ws.onclose = (e) => {
// connection closed
console.log(e.code, e.reason);
};
或fisbee
。