从 javascript es6 中的函数调用函数

Calling function from a function in javascript es6

我将 es6 javascript 与 babel 一起使用,并尝试使用 xhr 使用两个函数进行 ajax 调用,但出现错误 Uncaught TypeError: this.post is not a function

从 es6 class 中定义的另一个函数调用一个函数的正确语法是什么 javascript?

感谢您的回答这是我的代码

import alt from '../../alt';
import cookie from 'react-cookie';

class LoginActions {
  constructor(){
    this.generateActions(
      'updatePassword',
      'updateName',
      'loginSuccess',
      'loginFail',
      'remember'
    );
  }   
    // Generic get request
    post(url, data, callback) {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', url, true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    callback(null, xhr.responseText);
                } else {
                    callback(xhr.statusText);
                }
            }
        };
        xhr.send(data);
    }

    // Get actual content
    login(name, password, remember) {
      var data = "name="+name+"&password="+password+"&remember="+remember;
        this.post('api/login', data, function(err, data) {
            if (!err) {
              this.actions.loginSuccess(data.message);
            } else {
                this.actions.loginFail(JSON.parse(data.message));
            }
        }).bind(this);
    }




}

export default alt.createActions(LoginActions);

Edit1: 这就是我调用登录函数的方式/也将数据传递给上面的 xhr 请求

handleSubmit(event){
    event.preventDefault();

    var name = this.state.name;
    var password = this.state.password;
    var remember = this.state.remember;

    LoginActions.login(name, password, remember);

  }

您的方法 login()post() 是实例方法,不是静态方法。因此,您必须使用 new 创建 LoginActions 对象的实例,以便在该对象上正确调用这些方法。

或者如果您实际上不需要具有实例数据的实例,则将所有方法设为静态并将它们引用为 LoginActions.post()LoginActions.login(),而不是使用 this

相反,您正在尝试混合搭配。您正在调用 LoginActions.login(),这是一个静态类型调用,然后在 login() 内部,您正在尝试引用假定实例的 this

试试这些:

  1. 正如@jfriend00 所建议的那样,创建一个 LoginAction class 的实例并在其上调用登录方法:

    var loginAction = new LoginActions();
    loginAction.login(name, password, remember);

  2. 在 LoginActions 中定义 generateActions 方法 class。
  3. this.post('api/login', data, function(err, data) { if (!err) { this.actions.loginSuccess(data.message); } else { this.actions.loginFail(JSON.parse(data.message)); } }).bind(this);
    Here, you seem to be trying to bind this to the callback. But actually you are binding this to the return value of post method. To bind this to the callback, this.post('api/login', data, function(err, data) { if (!err) { this.actions.loginSuccess(data.message); } else { this.actions.loginFail(JSON.parse(data.message)); } }.bind(this));
    Notice function(){}.bind instead of the post(function(){}).bind