【发布时间】: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 的正确方法吗?
【问题讨论】:
-
[你可以简单地将它传递给像 window 这样的全局对象,然后在任何你想要的地方使用它](stackoverflow.com/a/71380705/11404554)