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
});
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句