【问题标题】:Dispatching redux action in axiosinterceptor (Non-react component)在 axiosinterceptor 中调度 redux 动作(非反应组件)
【发布时间】:2020-05-17 12:43:39
【问题描述】:

是否可以从不属于 react 组件的 javascript 对象调度 redux 函数?

通常,当我希望调度一个动作时,我会执行以下操作:

我会将 dispatch 函数映射到组件的 props :

const mapDispatchToProps = dispatch => {
  return {
    autoCheckState: () => dispatch(actions.authCheckState()),
  }
}

然后我可以像这样调用调度函数:

  async componentDidMount() {
    await this.props.autoCheckState();
    this.setState({
      checking:false
      })
  }

但是,现在我希望从我的 axiosinterceptor 对象中调用调度函数,并且它们没有“道具”

这是我设想的使用它的方式,但它当然不起作用:

axiosInstance.interceptors.response.use(
response => {
  return  response
},error => {

            ######## bunch of code that is not relevant ##########
            this.props.updateTokens(response.data.access,refreshToken)  #<--- how i would call it if i based it off the first example
            ######## bunch of code that is not relevant ##########
  return Promise.reject(error);
  }
);


const mapDispatchToProps = dispatch => {           ##<--- maping the dispatch to the 'props'
    return {
      updateTokens: () => dispatch(actions.authSuccess())
    }
  }


export default connect(mapStateToProps,mapDispatchToProps)(axiosInstance);

当然,上面的内容会给我这个没有定义的错误,因为它不是一个类。我可以知道在这种情况下使用 redux 的正确方法吗?

【问题讨论】:

标签: reactjs redux axios


【解决方案1】:

您可以使用 store.dispatch 从您的组件或动作创建者之外调度动作

import store from '/path/to/store';

axiosInstance.interceptors.response.use(
response => {
  return  response
},error => {
      store.dispatch(actions.authSuccess(response.data.access,refreshToken));
  return Promise.reject(error);
  }
);

【讨论】:

  • 非常感谢您的意见,这正是我所需要的!
猜你喜欢
  • 1970-01-01
  • 2017-09-08
  • 1970-01-01
  • 2019-12-24
  • 2017-05-14
  • 2017-09-28
  • 2021-01-22
  • 2019-02-07
  • 2018-01-26
相关资源
最近更新 更多