Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/457.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript reactjs async/await不';在第一次运行中,我们不能工作_Javascript_Reactjs_Async Await - Fatal编程技术网

Javascript reactjs async/await不';在第一次运行中,我们不能工作

Javascript reactjs async/await不';在第一次运行中,我们不能工作,javascript,reactjs,async-await,Javascript,Reactjs,Async Await,我有一个react应用程序, 我正在尝试使用redux和PHP进行登录 我有一个组件,该组件包含一个表单。用户输入密码并通过电子邮件发送到表单。提交表单后,数据进入一个名为handleSubmit的异步等待函数。 该函数在wait中有另一个名为onSubmitLogin的函数 从onSubmit转到ajax.js文件中的actiOn creator。 下一步是API PHP代码,其中PHP函数检查用户是否存在。 现在,通过mapStateToProps,从这里到减速器,再回到功能 我希望状态no

我有一个react应用程序, 我正在尝试使用redux和PHP进行登录

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

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

我希望状态
notActiveUserError
UserDoesNotExist
根据我使用
checkUserValidation
功能从减速器接收的props(
this.props.auth
)值而改变

我遇到的问题是,道具在第一次运行时会发生变化,但状态不会发生变化,每隔一段时间,它就会工作得很好,但在页面加载后的第一次,它就永远不会工作

任何帮助都会很好

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

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

动作创建者

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);
import React,{Component}来自'React';
从'react redux'导入{connect};
从“react router dom”导入{重定向,链接};
进口{
按钮
形式,
FormGroup,
FormControl,
上校,
警觉的,
网格,
一行
}来自“反应引导”;
从“../../actions”导入{userLogedIn};
从“../../actions/ajax”导入{userLogin};
类LoginForm扩展组件{
构造函数(){
超级();
这个州={
电子邮件:“”,
用户名:“”,
密码:“”,
作者:错,
用户名错误:“”,
密码错误:“”,
EmptyUsernameError:“”,
EmptyPasswordError:“”,
notActiveUserError:“”,
UserDoesNotExist:“”,
用户标识:“”
}
this.handleSubmit=this.handleSubmit.bind(this);
this.onChange=this.onChange.bind(this);
}
clientValidate=()=>{
假设isError=false;
如果(this.state.email===''){
这个.setState({emptyusernameserror:'emptyusernamerer:'emptyusernamerer:'emptyusernamerer:'emptyusernamerer:'emptyusernamerer:'emptyusernamerer:'emptyusernamerer:'emptyusernamerer:'emptyusernamerer:';
}
如果(this.state.password===''){
isError=真;
this.setState({EmptyPasswordError:'לאזנתםסימ});
}      
返回isError;
}
checkUserValidation(){
if(this.props.auth==false&&this.props.userid!==未定义){
console.log('this.props 1',this.props);
此.setState({notActiveUserError:';
}
if(this.props.auth==false&&this.props.userid==未定义){
日志('this.props 2',this.props);
这个.setState({UserDoesNotExist:'משש㪚אקים'});
}
}
onSubmitLogin(事件){
event.preventDefault();
if(this.clientValidate()){
this.clientValidate();
}否则{
让用户数据={
电子邮件:this.state.email,
密码:this.state.password
}
this.props.userLogin(userData);
}
}
handleSubmit=async(事件)=>{
等待此消息。onSubmitLogin(事件);
this.checkUserValidation();
}
重定向用户=()=>{
if(this.props.auth==true&&this.props.userid!=null){
const timestamp=new Date().getTime();//当前时间
const exp=timestamp+(60*60*24*1000*7)//添加一周
让auth=`auth=${this.props.auth};expires=${exp};
让userid=`userid=${this.props.userid};expires=${exp};
document.cookie=auth;
document.cookie=userid;
返回
}
}
onChange(事件){
这是我的国家({
[event.target.name]:event.target.value,
作者:错,
用户名错误:“”,
EmptyPasswordError:“”,
EmptyUsernameError:“”,
notActiveUserError:“”,
UserDoesNotExist:'
})
}
伊斯洛格丁=()=>{
log('this.props.auth',this.props.auth);
}
render(){
this.isLoggedIn();
返回(
התחבר
{this.redirectUser()}
שכחתי את הסיסמה
{
this.state.EmptyUsernameError?
{this.state.EmptyUsernameError}:
''
}
{
this.state.EmptyPasswordError?
{this.state.EmptyPasswordError}:
''
}
{
this.state.usernameError?
{this.state.usernameError}
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);
            });
    }
}
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);
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 });
            });
    }
}
onSubmitLogin(event){
    event.preventDefault();
    if(!this.clientValidate()){
        let userData ={
            email: this.state.email,
            password: this.state.password
        }
        this.props.userLogin(userData);
    }
}

handleSubmit = (event) => { 
    this.onSubmitLogin(event);
  // this.checkUserValidation // move this logic to reducer and set error there according to response
}

static getDerivedStateFromProps(nextProps, prevState) {
  // handle success/error according to your need and return update state
}