问题描述
import axios from "axios";
class ApiCaller {
CallApi = (SERVICE_URL,data) => {
return new Promise((resolve,reject) => {
axios.post(SERVICE_URL,data).then(function (response) {
var data = response.data
if (data.status) {
data = data.data
resolve(data)
} else {
if (data.isExpired != undefined && data.isExpired) {
console.log('here in expired')
}
reject(data.message)
}
}).catch(function (error) {
console.log(error);
reject(error)
});
})
}
}
export default new ApiCaller();
// export default connect()(new ApiCaller());
在这里,我正在调用整个应用程序中的所有Web服务 和data.isExpired是一个布尔值,其中服务器告诉我jwt令牌已过期,我需要从redux中删除用户信息并再次导航以登录,我已经使用了该方法将近50多个位置,我无法负担所有更改那些地方
如何从此处调度用户注销?
import { logoutUser } from "app/redux/actions/UserActions";
const mapStatetoProps = state => ({
logoutUser: PropTypes.func.isrequired
});
export default withRouter(connect(mapStatetoProps,{ logoutUser })(ApiCaller));
这可能是解决方案,要做到这一点,我需要扩展组件,它将破坏其他地方的ApiCaller实现
我也尝试过功能组件,但这并没有帮助,我需要从ApiCaller中注销,所以我不需要在每个视图上都处理jwt expire异常 我是React Redux的新手
任何人请
解决方法
我认为这是一个可以使用Redux Thunks的很好的例子。
// this is an action that can be dispatched to call the api
function callApi() {
return (dispatch) => {
apiCaller.CallApi()
.then(() => {
dispatch(callApiSuccess()); // success action defined elsewhere
})
.catch(() => {
dispatch(callApiError()); // error action defined elsewhere
});
}
}