redux 为什么我在action.js节上未定义[duplicate]

7cjasjjr  于 2022-12-19  发布在  其他
关注(0)|答案(1)|浏览(81)
    • 此问题在此处已有答案**:

How do I return the response from an asynchronous call?(44个答案)
When should I use a return statement in ES6 arrow functions(6个答案)
5天前关闭。

    • 我尝试从服务获取action.js文件的响应,但每次都未定义,我调试了service.js API函数,它显示了其响应,而我在action.js文件中未定义**
    • 操作. js**
export const loginUser = () => async (
  dispatch: ThunkDispatch<IStore, null, ILogInUserAction>,
  getState: () => IStore
) => {
  dispatch({ type: LOGIN_USER_ACCOUNT.LOGIN_USER_LOADING });

  const logInUser = store.getState().auth.logInUser;

  const payload: ILogInUserRequestAction = {
    username: logInUser.username,
    password: logInUser.password,
  };
  const result = await login(payload);
  console.log('result', result);
};
    • 示例. js**
import axios from 'axios';

export const instance = axios.create({
  baseURL: process.env.REACT_APP_BACK_END_HOST,
  headers: { 'Content-Type': 'application/json' },
});

instance.interceptors.response.use(
  (response) => response.data,
  (error) => Promise.reject(error)
);
    • 服务. js**
export const login = (data: ReqLogin) => {
  instance
    .post('/auth/login/', data)
    .then((response) => ({
      status: true,
      response,
    }))
    .catch((response) => ({
      status: false,
      error: response?.data,
    }));
};
    • 结果控制台日志**
    • 响应屏幕截图**
osh3o9ms

osh3o9ms1#

您没有在login()函数中返回任何内容。您必须添加return语句:

export const login = (data: ReqLogin) => {
   return instance
    .post('/auth/login/', data)
    .then((response) => ({
      status: true,
      response,
    }))
    .catch((response) => ({
      status: false,
      error: response?.data,
    }));
};

相关问题