当我在动作创建者中使用带有多个动作调度程序的redux thunk时,我的组件卡在循环中。这是我的action.js文件:
import * as types from './../constants/actionTypes';
export const fetchData = (id, data) => (dispatch) => {
dispatch({ type: types.BEGIN_API_CALL });
return myAPI.getData(id, data).then(
response => {
dispatch({
type: types.LOAD_DATA_SUCCESS,
response
});
},
error => {
dispatch({
type: types.API_CALL_ERROR,
message: error || 'Something went wrong.'
});
});
};
在我的api文件中,我正在尝试使用adal.js库调用我的服务进行身份验证。
这是我的api:
import { serviceConfig } from '../constants/appSettings';
class myAPI {
static getData(id, data) {
return new Promise((resolve, reject) => {
window.authContext.acquireToken(serviceConfig.resourceId, (errorDesc, token, error) => {
if (error) {
reject('Something is wrong with our service, please try again later!');
}
else {
resolve(fetch(`${serviceConfig.resourceBaseAddress}/Configuration/${id}`, {
headers: {
'Authorization': `Bearer ${token}`,
'Accept': 'application/json',
'Content-type': 'application/json'
},
method: "POST",
body: JSON.stringify(data)
}).then(response => {
if (response.status === 200) {
return response.json();
}
else if (response.status === 403 || response.status === 401) {
reject("You are not authorized to see this content!");
}
else {
reject(response.statusText);
}
})
);
}
});
});
}
}
export default myAPI;
当我在index.js文件中使用store.dispatch()时,它工作正常但是如果我连接我的组件并且在那个组件中生命cicyle方法调用fetchData()我得到无限循环,我一直在获取数据和componentDidMount每次都会调用()。 组成部分:
....
componentDidMount() {
this.props.fetchData("stringID", {});
}
....
export default connect(mapStateToProps, { fetchData })(withStyles(styles)(myComponent));