在 axiosinterceptor 中调度 redux 动作(非反应组件)

neo*_*hun 5 reactjs redux axios

是否可以从不属于 React 组件的 JavaScript 对象分派 Redux 函数?

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

我将把调度函数映射到组件的 props :

const mapDispatchToProps = dispatch => {
  return {
    autoCheckState: () => dispatch(actions.authCheckState()),
  }
}
Run Code Online (Sandbox Code Playgroud)

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

  async componentDidMount() {
    await this.props.autoCheckState();
    this.setState({
      checking:false
      })
  }
Run Code Online (Sandbox Code Playgroud)

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

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

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);
Run Code Online (Sandbox Code Playgroud)

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

Shu*_*tri 4

您可以使用 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);
  }
);
Run Code Online (Sandbox Code Playgroud)