reactjs async / await在第一次运行中不起作用

时间:2019-11-21 07:34:39

标签: javascript reactjs async-await

我有一个React应用, 我正在尝试使用redux和PHP执行登录。

我有一个组件,该组件包含一个表格。用户输入密码并通过电子邮件发送给表单。提交表单后,数据进入名为handleSubmit的异步等待函数。 该函数在等待中还有另一个名为onSubmitLogin的函数。

onSubmit转到actiOn creator文件中的ajax.js。 下一步是API PHP代码,其中PHP函数检查用户是否存在。 现在从那里到减速器,然后通过mapStateToProps返回功能,

我希望状态notActiveUserErrorUserDoesNotExist根据我使用this.props.auth函数从减速器获得的道具(checkUserValidation)值而改变。

我遇到的问题是道具在第一次运行时就发生了变化,但状态并没有发生变化,每隔一次它的运行效果就很棒,但是在页面加载后的第一次运行中却从未运行过。

任何帮助都会很棒。

这是我的代码: handleSubmit 位于LoginForm.js中(完整组件位于问题的底部)

handleSubmit = async (event) => { 
    await this.onSubmitLogin(event);
    this.checkUserValidation();
}

onSubmitLogin 位于LoginForm.js中(完整组件位于问题的底部)

onSubmitLogin(event){
    event.preventDefault();

    if(this.clientValidate()){
        this.clientValidate();
    }else{
        let userData ={
            email: this.state.email,
            password: this.state.password
        }
        this.props.userLogin(userData);
    }
}

动作创建者

export const userLogin = (userData) => {
    return (dispatch) => {
        axios({
                url: `${API_PATH}/users/Login.php`,
                method: 'post',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                data: JSON.stringify(userData)
            })
            .then(function(response) {
                dispatch({ type: USER_LOGIN, value: response.data });
            })
            .catch(function(error) {
                console.log(error);
            });
    }
}

LoginForm组件:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Redirect, Link  } from 'react-router-dom';
import {
    Button,
    Form,
    FormGroup,
    FormControl,
    Col,
    Alert,
    Grid,
    Row
} from 'react-bootstrap';

import { userLogedIn } from '../../actions'; 
import { userLogin } from '../../actions/ajax'; 


class LoginForm extends Component {
    constructor() {
        super();
        this.state={
            email: '',
            username: '',
            password: '',
            auth: false,
            usernameError: '',
            passwordError: '',
            EmptyUsernameError: '',
            EmptyPasswordError: '',
            notActiveUserError: '',
            UserDoesNotExist: '',
            userid: ''
        }
        this.handleSubmit = this.handleSubmit.bind(this);
        this.onChange = this.onChange.bind(this);

    }


    clientValidate = () => {
        let isError = false;

        if(this.state.email === ''){

            this.setState({EmptyUsernameError: 'לא הזנתם דואר אלקטרוני'});
        }
        if(this.state.password === ''){
            isError = true;
            this.setState({EmptyPasswordError: 'לא הזנתם סיסמה'});
        }      
        return isError;
    }

    checkUserValidation(){
        if(this.props.auth === false && this.props.userid !== undefined){
            console.log('this.props 1', this.props);
            this.setState({notActiveUserError: 'חשבון לא מאומת'});
        }
        if(this.props.auth === false && this.props.userid === undefined){
            console.log('this.props 2', this.props);
            this.setState({UserDoesNotExist: 'משתשמ לא קיים'});
        }
    }

    onSubmitLogin(event){
        event.preventDefault();

        if(this.clientValidate()){
            this.clientValidate();
        }else{
            let userData ={
                email: this.state.email,
                password: this.state.password
            }
            this.props.userLogin(userData);
        }
    }

    handleSubmit = async (event) => { 
        await this.onSubmitLogin(event);
        this.checkUserValidation();
    }


    redirectUser = () => {    
        if(this.props.auth === true && this.props.userid != null){
            const timestamp = new Date().getTime(); // current time
            const exp = timestamp + (60 * 60 * 24 * 1000 * 7)                // add one week

            let auth = `auth=${this.props.auth};expires=${exp}`;
            let userid = `userid=${this.props.userid};expires=${exp}`;

            document.cookie = auth;
            document.cookie = userid;

            return <Redirect to='/records/biblist' />
        }
    }


    onChange(event){
        this.setState({
            [event.target.name]: event.target.value,
            auth: false,
            usernameError: '',
            EmptyPasswordError: '',
            EmptyUsernameError: '',
            notActiveUserError: '',
            UserDoesNotExist: ''
        })


    }

    isLoggedIn = () =>{
        console.log(' this.props.auth ',  this.props.auth);

    }

    render() {
        this.isLoggedIn();
        return (

                        <Form>

                            <FormGroup  controlId="formHorizontalusername">
                                <Col xs={12} sm={5} style={TopMarginLoginBtn}>
                                <Row style={marginBottomZero}>
                                    <FormControl ref="email" name="email" type="email" onChange={this.onChange} placeholder="דואר אלקטרוני" aria-label="דואר אלקטרוני"/>
                                </Row>
                                </Col>
                                <Col xs={12} sm={4} style={TopMarginLoginBtn}>
                                <Row style={marginBottomZero}>
                                    <FormControl ref="password" name="password" type="password" onChange={this.onChange} placeholder="הקלד סיסמה" aria-label="סיסמה"/>
                                    </Row>
                                </Col>

                                <Col  xs={12} sm={3} style={TopMarginLoginBtn} >

                                    <Button onClick={this.handleSubmit} type="submit" className="full-width-btn" id="loginSubmit">התחבר</Button>
                                    {this.redirectUser()}
                                    </Col>
                                    <Col xs={12}>
                                    <Link to="/passwordrecovery">שכחתי את הסיסמה</Link>
                                </Col>
                            </FormGroup>
                            {
                                this.state.EmptyUsernameError ? 
                                <Alert bsStyle="danger"> {this.state.EmptyUsernameError} </Alert> :
                                ''
                            }
                            {
                                this.state.EmptyPasswordError ? 
                                <Alert bsStyle="danger"> {this.state.EmptyPasswordError} </Alert> :
                                ''
                            }

                            {
                                this.state.usernameError ? 
                                <Alert bsStyle="danger"> {this.state.usernameError} </Alert> :
                                ''
                            }
                             {
                                 //PROBLEM!! state updates before props
                                 this.state.notActiveUserError ? 
                                <Alert bsStyle="danger">{this.state.notActiveUserError}</Alert> :
                                ''
                            }
                            {
                                //PROBLEM!! state updates before props
                                this.state.UserDoesNotExist ? 
                                <Alert bsStyle="danger">{this.state.UserDoesNotExist} </Alert> :
                                ''
                            }

                            <Row className="show-grid">

                        </Row>
                        </Form>



        );
    }
}
const bold={
    fontWeight: 'bolder'
}
const mapDispatchToProps = dispatch => {
    return {
        userLogedIn: (params) => dispatch(userLogedIn(params))
    };
};


const mapStateToProps = state => {
    return {
        userid: state.authReducer.userid,
        auth: state.authReducer.auth,
        email: state.authReducer.email
    }
}

export default connect(mapStateToProps, {userLogedIn, userLogin})(LoginForm);

1 个答案:

答案 0 :(得分:1)

如果要在组件中使用async-await,则必须将API调用移至组件,因为从组件调用操作时,它不会将数据返回给组件。

如果您要使用redux,那么我建议您从组件中删除async-await,它将无法正常工作,而应使用redux状态存储成功或失败状态,并处理{{1} }

getDerivedStateFromProps

在您的组件中

export const userLogin = (userData) => {
    return (dispatch) => {
        dispatch({ type: USER_LOGIN_BEGIN }); // reset error/login state
        axios({
                url: `${API_PATH}/users/Login.php`,
                method: 'post',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                data: JSON.stringify(userData)
            })
            .then(function(response) {
                dispatch({ type: USER_LOGIN, value: response.data });
            })
            .catch(function(error) {
                dispatch({ type: USER_LOGIN_FAILED, value: error });
            });
    }
}