【问题标题】:How to fix "undefined" issue in async call to dispatch in action creator of redux?如何解决异步调用中的“未定义”问题以在 redux 的操作创建者中分派?
【发布时间】:2019-09-09 20:04:18
【问题描述】:

我正在制作一个反应应用程序,实现身份验证以使用 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 获取的控制台上,或者以更解释的方式,我想从调用者的动作调用中返回获取的结果。即token: any token

【问题讨论】:

  • 您可以使用选择器(如paruchuri-p 的答案),也可以在authUser 操作函数中返回最后一个.then 中的内容。现在它正确调度,但隐式返回undefined
  • 是的,只需在您的 dispatch({type: AUTH_USER, payload: results}) 通话后添加 return results
  • @Brandon 兄弟非常感谢我已经得到了我想要的东西,非常感谢你让我开心了兄弟!

标签: javascript reactjs redux react-redux redux-thunk


【解决方案1】:

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

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

connect(mapStateToProps, {authUser})(Login)

您现在可以使用 this.props.tokenthis.props.errors 在您的组件中访问它

【讨论】:

  • 应该是 tokenerrors 而不是 usernamepassword,因为这是 OP 将其有效负载减少到的原因。
  • 哈哈。是的。谢谢!
  • 我在问这个问题之前已经完成了这个,我已经在我的组件中得到了这个,但我也想在调用动作函数之后把它们放在 .then() 中,因为我需要那里的令牌请帮助我用那个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
  • 1970-01-01
  • 1970-01-01
  • 2018-12-08
  • 1970-01-01
  • 2018-09-15
  • 1970-01-01
相关资源
最近更新 更多