[英]How do i dispatch a redux action from class and not component
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
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.