繁体   English   中英

我如何从类而不是组件调度 redux 操作

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM