【问题标题】:How do i dispatch a redux action from class and not component我如何从类而不是组件调度 redux 操作
【发布时间】:2020-12-20 01:02:35
【问题描述】:
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 的新手

请大家

【问题讨论】:

  • 你试过reduxStore.dispatch(logoutUser())吗?
  • 无法访问。

标签: node.js reactjs redux react-redux express-jwt


【解决方案1】:

我认为这是一个很好的例子,说明你可以在哪里使用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
      });
  }
}

【讨论】:

    猜你喜欢
    • 2018-03-24
    • 2018-11-20
    • 2016-11-23
    • 1970-01-01
    • 2016-06-06
    • 2018-05-13
    • 1970-01-01
    • 2017-07-08
    • 2017-04-03
    相关资源
    最近更新 更多