【问题标题】:How to update state from axios interceptor如何从 axios 拦截器更新状态
【发布时间】:2021-07-15 05:30:03
【问题描述】:

我希望有一个通用的方法来显示错误。我尝试添加响应拦截器,但我的状态没有更新。

interceptor.js

import {showError} from "./actions";
const axiosInstance = axios.create();

axiosInstance.interceptors.response.use(
    response => response,
    error => {
        showError(error);
    }
);

export default axiosInstance;

actions.js

export const showError = (error) => {
    return ({
        type: SHOW_ERROR,
        payload: error.response
    })
}

reducer.js

const INITIAL_STATE = {errorData: ''};

const reducer = (state = INITIAL_STATE, action) => {
    switch (action.type) {
        case SHOW_ERROR:
            return {
                ...state,
                errorData: action.payload.data.translationKey,
            }
    }
}

我已经完成了所有导入,我可以在操作中看到错误,但我的状态没有得到更新。没有调用减速器。

有没有办法直接从拦截器更新状态?我想避免捕获每个 api 调用的错误。

【问题讨论】:

标签: reactjs redux


【解决方案1】:

尝试使用如下调度:

import {showError} from "./actions";
import reduxStore from './store'; << your redux store

const axiosInstance = axios.create();
const {dispatch} = reduxStore;

axiosInstance.interceptors.response.use(
    response => response,
    error => {
        dispatch(showError(error));
    }
);

export default axiosInstance;

【讨论】:

  • useDispatch 不能在组件外使用
  • @DanielDuong 是的,你是对的。我已将其编辑为使用商店调度
  • @Rukshán redux 开发工具显示更新,但由于某种原因,当我记录状态时它没有改变。知道为什么会发生这种情况吗?如果我在发出请求的地方(不在拦截器中)发现错误,它可以正常工作
  • 你在使用 console.log 吗?我猜它不适用于 redux 商店。改用 redux-logger。 stackoverflow.com/questions/36534182/…
【解决方案2】:

如果你使用 redux Thunk 作为中间件

export const showError = (error) => dispatch => {
    return ({
        type: SHOW_ERROR,
        payload: error.response
    })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-15
    • 2018-11-27
    • 2018-11-27
    • 2022-11-09
    • 2021-05-04
    • 2018-03-03
    • 2021-08-06
    • 2019-06-26
    相关资源
    最近更新 更多