如何在使用 redux 时显示对组件的 api 调用的响应?

How to display response from an api call to a component whilst using redux?

我正在尝试在我的项目中实施身份验证系统,并且一直在学习本教程 https://youtu.be/LKlO8vLvUao。 该系统工作但是我试图在登录尝试失败时显示错误消息并且我无法弄清楚如何将错误消息从减速器获取到我想要显示它的组件(最好使用 [msg,setMsg ]勾)

这是我捕获错误响应并将其传递给 reducer 的操作代码:

export const signin = (formData, history) => async (dispatch) => {
try {
    const { data }  = await API.signIn(formData);
    dispatch({ type: AUTH, data });

    history.push('/')
}
catch (error){
    const data = error.response.data;
    dispatch({ type: "AUTH_FAIL", data })

 }
}

这是我的减速器:

import { AUTH, LOGOUT } from '../constants/actionTypes'

const authReducer = (state = { authData: null }, action) => {
   switch (action.type){
      case AUTH:
        localStorage.setItem('profile', JSON.stringify({ ...action?.data }))
        return { ...state, authData: action?.data};
      case LOGOUT:
        localStorage.clear();
        return { ...state, authData: null };
    case "AUTH_FAIL":
        return { ...state, authData: action?.data};

    default:
        return state;
}
}

export default authReducer; 

在您为这个减速器定义状态的地方,将其分成两个 parts.one 现在是 authData,第二个是错误。当调度 AUTH_FAIL 时,你应该在 reducer 中 return 是错误而不是 authData。现在在您的组件中,您可以随意调用状态并使用更新后的状态。我知道有两种方法可以做到这一点: 1-mapStatetoProps 2-store.subscribe()store.getState()

在 Reducer 中创建 initiateState 对象

const initiateState: {
authData: null,
error: null
}

就像你在行动中所做的那样

catch (error){
    **const data = data.response.error;**
    dispatch({ type: "AUTH_FAIL", data })

 }

也改reducer,将action.data的数量发送给error

const authReducer = (state = initiateState, action) => {
   ....//your code
       case "AUTH_FAIL":
        return { ...state, error: action.data};

    default:
        return state;
   }
}

使用挂钩 这等于 mapStateToProps

  const error= useSelector((state) => state.error)