[英]Dispatching redux action in axiosinterceptor (Non-react component)
is it possible to dispatch a redux function from a javascript object that is not part of react's component?是否可以从 javascript ZA8CFDE6331BD59EB2AC96F8911C4B6 组件中派发 redux function?
Usually when i wish to dispatch an action, i would do the following:通常,当我希望调度一个动作时,我会执行以下操作:
I'll map the dispatch function to the component's props:我将 map 调度 function 到组件的道具:
const mapDispatchToProps = dispatch => {
return {
autoCheckState: () => dispatch(actions.authCheckState()),
}
}
And then i can just call the dispatch function like this:然后我可以像这样调用调度 function:
async componentDidMount() {
await this.props.autoCheckState();
this.setState({
checking:false
})
}
However, now i wish to call the dispatch function from within my axiosinterceptor object, and they don't have "props"但是,现在我希望从我的 axiosinterceptor object 中调用调度 function,并且他们没有“道具”
Here is what i envisioned would be the way to use it, but ofcourse it does not work:这是我设想的使用它的方式,但它当然不起作用:
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);
Ofcourse the above would give me the error that this is not defined, since its not a class.当然,上面会给我这个没有定义的错误,因为它不是 class。 May i know the correct way of using redux in such a situation?
我可以知道在这种情况下使用 redux 的正确方法吗?
You can make use of store.dispatch to dispatch an action from outside of your components or action creators您可以使用 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);
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.