如何解决异步调用中的 "undefined" 问题以分派 redux 的动作创建者?

How to fix "undefined" issue in async call to dispatch in action creator of redux?

我正在制作一个 React 应用程序,实施身份验证以使用 API 调用从服务器获取提供凭据的令牌。我的方法是否完美?

我在后端使用 Django API,在前端使用 reactJS,还使用 ​​thunk 作为 redux 的中间件。

authAction.js

import {AUTH_USER} from "./types";

export const authUser = (username, password) =>
{
    return (dispatch) => {
        const data = {
            username: username,
            password: password
        }
        return fetch("http://127.0.0.1:8000/api/v1/login/auth/", {
            method: 'POST',
            body: JSON.stringify(data),
            headers: {'Content-Type': 'application/json'}
        })
            .then(results => results.json())
            .then(results => {
                dispatch({
                type: AUTH_USER,
                payload: results
            })
            }
            )
    }
}

authReducer.js

import {AUTH_USER} from "../actions/types";

const initialState = {
    errors: [],
    token : '',
}
export default function (state=initialState,action) {
    switch (action.type) {
        case AUTH_USER:
            return {
                ...state,
                token:action.payload.token,
                errors:action.payload.errors,
            }
        default:
            return state
    }
}

登录功能

login(e){
        e.preventDefault();
        if(this.state.username && this.state.password){
            console.log("Login");
            this.props.authUser(this.state.username,this.state.password)
                .then(res=>console.log(res)) // undefined
        }
}

我想在控制台上打印从 API 获取的结果,或者以更解释的方式我想 return 从操作调用中获取的结果呼叫者。即 token: any token

这样不行。当您执行操作时,在异步调用之后,您将对结果进行分派,并将结果通过 reducer 添加到商店中。您需要通过连接到商店从商店中获取值。

const mapStateToProps = ({
  token, errors
}) => ({
  token,
  errors
});

connect(mapStateToProps, {authUser})(Login)

您现在可以使用 this.props.token & this.props.errors

在您的组件中访问它