我有一个React.js应用程序。
      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)
            }
        });
    }如果我点击一个按钮,应该会执行函数getData()。但是如果这个函数被执行,我会在浏览器中得到这个错误的TypeError: Cannot read property 'username' of undefined。
下面是我调用函数的方式:
<input type="input" value={this.state.username} onChange={this.handleChangeUsername} className="form-control" placeholder="Email" />
发布于 2021-05-13 18:04:54
this正在引用beforeSend函数,请尝试使用箭头函数将其删除
beforeSend: (xhr) => { // change to arrow
       xhr.setRequestHeader('Authorization', make_base_auth(this.state.username, this.state.password));
},https://stackoverflow.com/questions/67517319
复制相似问题