[英]Dispatching redux action in axiosinterceptor (Non-react component)
是否可以從 javascript ZA8CFDE6331BD59EB2AC96F8911C4B6 組件中派發 redux function?
通常,當我希望調度一個動作時,我會執行以下操作:
我將 map 調度 function 到組件的道具:
const mapDispatchToProps = dispatch => {
return {
autoCheckState: () => dispatch(actions.authCheckState()),
}
}
然后我可以像這樣調用調度 function:
async componentDidMount() {
await this.props.autoCheckState();
this.setState({
checking:false
})
}
但是,現在我希望從我的 axiosinterceptor object 中調用調度 function,並且他們沒有“道具”
這是我設想的使用它的方式,但它當然不起作用:
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);
當然,上面會給我這個沒有定義的錯誤,因為它不是 class。 我可以知道在這種情況下使用 redux 的正確方法嗎?
您可以使用 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.