Javascript 在axios拦截器中使用时,redux调度不起作用
我想在axios返回错误时显示snackbar。 我对配置snackbar使用reduxJavascript 在axios拦截器中使用时,redux调度不起作用,javascript,reactjs,redux,react-redux,axios,Javascript,Reactjs,Redux,React Redux,Axios,我想在axios返回错误时显示snackbar。 我对配置snackbar使用redux axiosAgent.interceptors.response.use( function(response) { return response; }, function(error) { console.log('object') const dispatch = useDispatch(); dispatch({ type: ActionsTy
axiosAgent.interceptors.response.use(
function(response) {
return response;
},
function(error) {
console.log('object')
const dispatch = useDispatch();
dispatch({
type: ActionsTypes.CHANGE_SNACKBAR_CONFIG,
payload: { variant: "error", message: Strings.errors.problem }
});
dispatch({ type: ActionsTypes.CHANGE_SNACKBAR_SHOW, payload: true });
return Promise.reject(error);
}
);
这是我的snackbar组件:
export default function Snackbar() {
const open = useSelector(state => state.Snackbar.showSnackbar);
const config = useSelector(state => state.Snackbar.snackbarConfig);
const dispatch = useDispatch();
const handleClose = (event, reason) => {
if (reason === "clickaway") {
return;
}
dispatch({ type: ActionsTypes.CHANGE_SNACKBAR_SHOW, payload: false });
};
useEffect(() => {
console.log(config);
}, [config]);
return (
<SB open={open} autoHideDuration={6000} onClose={handleClose}>
<Alert onClose={handleClose} severity={config.variant}>
{config.message}
</Alert>
</SB>
);
}
导出默认函数Snackbar(){
const open=useSelector(state=>state.Snackbar.showSnackbar);
const config=useSelector(state=>state.Snackbar.snackbarConfig);
const dispatch=usedpatch();
const handleClose=(事件、原因)=>{
如果(原因==“单击离开”){
返回;
}
分派({type:ActionsTypes.CHANGE\u SNACKBAR\u SHOW,payload:false});
};
useffect(()=>{
console.log(config);
},[config]);
返回(
{config.message}
);
}
但是不起作用。
当我从组件中分派它时,它工作,但在这里不工作。钩子,例如
useDispatch()
,只能在函数组件的主体中使用。您不能在拦截器中使用useDispatch
。如果需要在拦截器中分派操作,则需要有对存储
对象的引用,并调用存储。分派(/*action*/)
使用分派
必须在React组件的上下文中调用。