如何使用 react-redux 从函数中检索返回值/对象并存储在变量中?

范例

我是 react-redux 环境的新手,一直在做一个小项目来熟悉。目前,我正在登录页面上工作,无论成功与否,我都能够成功检索响应。我面临的问题是,一旦我检索到响应,我不知道如何在没有 console.log 的情况下存储和读取响应中的内容。

import React from 'react';
import { connect } from 'react-redux';
import { Button, Input } from 'reactstrap';
import { IsEmpty } from '../../helpers/utils';
import { userActions } from '../../actions/user.actions';

import  LoginLayoutComponent  from '../layouts/loginLayout';

class LoginFormComponent extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            Username: '',
            Password: '',
            submitted: false,
            errors: {}
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleValidation = this.handleValidation.bind(this);
    }

    handleChange(e) {
        const { name, value } = e.target;
        this.setState({ [name]: value });
    }

    handleSubmit(e) {
        e.preventDefault();        

        let response = null;
        let errors = {};
        if (this.handleValidation()) {   

            this.setState({ submitted: true });
            const { Username, Password } = this.state;            

            if (Username && Password) {
                response = JSON.stringify(userActions.login(Username, Password));
                console.log(response);    
                if (response != null) {
                    errors["Error"] = "Invalid Username or Password";
                    this.setState({
                        errors: errors
                    });
                }
            }
        }
    }

    handleValidation() {

        let isValid = true;
        let errors = {};
        if (this.state.submitted === true && IsEmpty(this.state.Username)) {
            errors["Username"] = "Username is required";
            isValid = false;
        }
        if (this.state.submitted === true && IsEmpty(this.state.Password)) {
           errors["Password"] = "Password is required";
            isValid = false;
        }
        this.setState({
            errors: errors
        });
        return isValid;
    }

    render() {

        const { Username, Password, submitted, errors } = this.state;    
        //var errorMessage = loginErrorMessage;

        return (
            <LoginLayoutComponent>
                <div className="panel panel-default">
                    <div className="panel-heading"></div>
                    <div className="panel-body" autoFocus={false}>
                        <form method="post" name="LoginForm" onSubmit={this.handleSubmit}>
                            <div className='form-group row'>
                                <input className='form-control' type="text" placeholder="Username" name="Username" value={Username} onChange={this.handleChange} autoFocus />                           
                            {!IsEmpty(errors.Username) && <p>{errors.Username}</p>}
                           </div>                    
                            <div className='form-group row' >                           
                                <Input className="form-control" type="Password" placeholder="Password" name="Password" value={Password} onChange={this.handleChange} />
                                {!IsEmpty(errors.Password) && <p>{errors.Password}</p>}
                            </div>                        
                            <Button className="btn btn-warning btn-block" onClick={this.handleSubmit}>Login</Button>                   
                        </form>
                        {!IsEmpty(errors.Response) && <p><b>Login Failed</b>.{errors.Response}</p>}
                    </div>
                </div>
            </LoginLayoutComponent>
        );
    }
}
function mapStateToProps(state) {
    //const { loading } = state.authentication;
    return {
    //    loginErrorMessage: state.authentication.error && state.authentication.error.message
    };
}
const LoginForm = connect(mapStateToProps)(LoginFormComponent);
export { LoginForm };
=======================================================================
Action
import { history } from '../helpers/history';
import { userService } from '../services/user.service';
import { userConstants } from '../constants/user.constants';

export const userActions = {
    login,
    logout
};

function login(Username, Password) {

    //return dispatch => {
    console.log('Action begin');
        userService.login(Username, Password)
            .then(
                results => {
                    if (results.username) {
                        console.log('success');  
                        history.push('/home');
                        return { type: userConstants.LOGIN_SUCCESS, Username };
                    }                    
            }, error => {    

                        return { error };
                }
            );
    //};   
}
====================================================================
Service
import { HandleResponse, Logout } from '../helpers/utils';


export const userService = {
    login,
    logout,
    _setUserSession
};

function login(Username, Password) {

      const requestOptions = {
        method: 'POST',      
        headers: new Headers({
            'Content-Type': 'application/json; charset=utf-8'            
        }),
        body: JSON.stringify({
            Username,
            Password
        })
    };
    const requestPath = "http://localhost:53986/api/login/postlogin";
    console.log('Start Fetching');
    return fetch(requestPath,requestOptions)
        .then(HandleResponse)
        .then(response => {         

            var result = response && response.results && response.results.length > 0 ? response.results[0] : null;           
            if (result) {
                console.log('Setting session');
                _setUserSession(result);
            }
            return {result};
        }).catch(function (error) {  
            return Promise.reject(error);
        });
}

 // Login successful :: store user details 
function _setUserSession(user) {   
    if (user.id) {
        localStorage.setItem('user', JSON.stringify(user));        
    }
}
===========================================
IsEmpty (As requested)

export function IsEmpty(param) {
    return param === null || param === undefined || param === "" || (typeof param === "object" && param.length === 0) || param === false || param === 0;
}

预期的结果是在响应中显示错误并将其显示在登录表单上给用户。

托马斯·阿博纳

问题在于您在两个login函数中使用 promise 的方式

function login(Username, Password) {

    //return dispatch => {
    console.log('Action begin');
        userService.login(Username, Password)
            .then(
                results => {
                    if (results.username) {
                        console.log('success');  
                        history.push('/home');
                        return { type: userConstants.LOGIN_SUCCESS, Username };
                    }                    
            }, error => {    

                        return { error };
                }
            );
    //};   
}

当你return在这个函数中时,它返回then回调而不是login函数。

您可以使用 es6 async/await语法修复您的函数(代码可能有误,但想法在这里):

async function login(Username, Password) {
  try {
    const res = await userService.login(Username, Password);
    if (results.username) {
      console.log('success');  
      history.push('/home');
      return { type: userConstants.LOGIN_SUCCESS, Username };
    }         
  } catch (e) {
    return error;
  }                     
}

async function login(Username, Password) {
  const requestOptions = {
    method: 'POST',      
    headers: new Headers({
      'Content-Type': 'application/json; charset=utf-8'            
    }),
    body: JSON.stringify({
      Username,
      Password
    })
  };
  const requestPath = "http://localhost:53986/api/login/postlogin";
  console.log('Start Fetching');
  const response = HandleResponse(await fetch(requestPath,requestOptions));
  const result = response && response.results && response.results.length > 0 ? response.results[0] : null;           
  if (result) {
    console.log('Setting session');
    _setUserSession(result);
  }
  return result;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何使用 React/Redux 更新存储中的特定对象?

来自分类Dev

如何使用redux在react中获取数据?

来自分类Dev

React / Redux-如何在React组件中显示Redux存储中的值?

来自分类Dev

如何使用渲染React / Redux中定义的变量作为回报?

来自分类Dev

如何在react redux中存储多层对象?

来自分类Dev

如何从异步函数到React Native中的变量获取返回值?

来自分类Dev

如何使用Redux解决React JS中的401错误?

来自分类Dev

如何使用 react-redux 连接外部包中的组件

来自分类Dev

无论缓存如何,如何在React中更新Redux存储

来自分类Dev

如何在 React Redux 中渲染 ListItems?

来自分类Dev

Redux 存储在 React 类组件中返回空值

来自分类Dev

React 表示组件无法使用 React 容器从 redux 存储中读取 <input /> 的值

来自分类Dev

使用React(与Redux)作为网站中的组件

来自分类Dev

使用Redux在React中调度动作的问题

来自分类Dev

使用 Redux 的组件中的 React-Dates

来自分类Dev

如何在react-redux中更新存储状态?

来自分类Dev

使用Redux在React中更新数组中的嵌套对象

来自分类Dev

如何使用currying在React中创建HoC并同时连接到Redux存储?

来自分类Dev

如何在获取操作中使用存储中的数据(react-redux)

来自分类Dev

如何在React Redux中渲染Date对象?

来自分类Dev

在React JS功能组件中分派动作后,如何立即使用Redux存储中的更新值

来自分类Dev

如何使用thunk和useDispatch(react-redux挂钩)从操作中返回承诺?

来自分类Dev

调用动作时,如何在React Redux中更改数组中对象的值?

来自分类Dev

react-redux如何获取提供者的存储对象?

来自分类Dev

如何从React Native中的异步JS函数返回变量的值

来自分类Dev

我如何在React中使用React / Redux表单获取帖子值

来自分类Dev

如何在React和Redux中使用从asyncValidate函数返回的数据?

来自分类Dev

如何使用react-router-redux routeActions?

来自分类Dev

如何在React中使用Redux的Provider

Related 相关文章

  1. 1

    如何使用 React/Redux 更新存储中的特定对象?

  2. 2

    如何使用redux在react中获取数据?

  3. 3

    React / Redux-如何在React组件中显示Redux存储中的值?

  4. 4

    如何使用渲染React / Redux中定义的变量作为回报?

  5. 5

    如何在react redux中存储多层对象?

  6. 6

    如何从异步函数到React Native中的变量获取返回值?

  7. 7

    如何使用Redux解决React JS中的401错误?

  8. 8

    如何使用 react-redux 连接外部包中的组件

  9. 9

    无论缓存如何,如何在React中更新Redux存储

  10. 10

    如何在 React Redux 中渲染 ListItems?

  11. 11

    Redux 存储在 React 类组件中返回空值

  12. 12

    React 表示组件无法使用 React 容器从 redux 存储中读取 <input /> 的值

  13. 13

    使用React(与Redux)作为网站中的组件

  14. 14

    使用Redux在React中调度动作的问题

  15. 15

    使用 Redux 的组件中的 React-Dates

  16. 16

    如何在react-redux中更新存储状态?

  17. 17

    使用Redux在React中更新数组中的嵌套对象

  18. 18

    如何使用currying在React中创建HoC并同时连接到Redux存储?

  19. 19

    如何在获取操作中使用存储中的数据(react-redux)

  20. 20

    如何在React Redux中渲染Date对象?

  21. 21

    在React JS功能组件中分派动作后,如何立即使用Redux存储中的更新值

  22. 22

    如何使用thunk和useDispatch(react-redux挂钩)从操作中返回承诺?

  23. 23

    调用动作时,如何在React Redux中更改数组中对象的值?

  24. 24

    react-redux如何获取提供者的存储对象?

  25. 25

    如何从React Native中的异步JS函数返回变量的值

  26. 26

    我如何在React中使用React / Redux表单获取帖子值

  27. 27

    如何在React和Redux中使用从asyncValidate函数返回的数据?

  28. 28

    如何使用react-router-redux routeActions?

  29. 29

    如何在React中使用Redux的Provider

热门标签

归档