简体   繁体   中英

TypeError: Cannot read property 'username' of undefined React.js

Well I have a React.js application.

      constructor(props){
        super(props);
        this.state = {
            password:'',
            username:''
        }
        this.handleChangePassword = this.handleChangePassword.bind(this)
        this.handleChangeUsername = this.handleChangeUsername.bind(this)
        this.getData = this.getData.bind(this)
    }
    handleChangePassword(event) {
        this.setState({password: event.target.value});
    }
    handleChangeUsername(event) {
        this.setState({username: event.target.value});
    }
   getData() {
        $.ajax({
            type: 'GET',
            url: `/home/data`,
            dataType: 'json',
            //whatever you need
            beforeSend: function (xhr) {
                xhr.setRequestHeader('Authorization', make_base_auth(this.state.username, this.state.password));
            },
            success: function(xhr){
                console.log(xhr.status)
            }
        });
    }

If I click on a button the function getData() should be executed. But if this function gets executed I'm getting this error TypeError: Cannot read property 'username' of undefined in the browser.

This is how I call the function:

<input type="input" value={this.state.username} onChange={this.handleChangeUsername} className="form-control" placeholder="Email" />

the this is referring to the beforeSend function, try arrow function to get rid of it

beforeSend: (xhr) => { // change to arrow
       xhr.setRequestHeader('Authorization', make_base_auth(this.state.username, this.state.password));
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM