在方法内部调用另一个方法 ReactJS

Calling inside a method another method ReactJS

本文关键字:方法 ReactJS 另一个 内部 调用      更新时间:2023-09-26

首先,我是 React 的新手,所以如果有什么需要改进的地方告诉我。

有一个登录表单,将带有ajax的信息发送到php,我想捕获错误并更新p元素,尽管我找不到方法。

当我用php发送的消息是错误的时,我想调用另一个方法,但它说未定义。

   var APP = React.createClass({
    getInitialState:function(){
      return{user:'',pass:'',message:''};
    },
    setUser:function(e){
      this.setState({user:e.target.value});
    },
    setPass:function(e){
      this.setState({pass:e.target.value});
    },
    setErrors:function(errors){
      alert('calling');
      this.setState({message:errors});
    },
    handleForm:function(e){
      e.preventDefault();
      var username = this.state.user;
      var password = this.state.pass;

      $.ajax({
        'url':'prg/loginJSON.php',
        'type':'POST',
         data:{'username':username,'password':password},
         success:function(result){
           if(result.error){
             window.location.href="http://localhost/learnSeries/home.html";
             sessionStorage.setItem('cookiePass',result.token);
           }
           else{
             this.setErrors(result.message);
           }
         },
         error:function(xhr){
           console.log('error ajax' +xhr.responseText);
         }
      });
    },
    render:function(){
    return(
      <form onSubmit={this.handleForm}  id="loginForm" method="post" action="" role="form">
        <label className="is-required">User</label>
        <input type="text"  name="username" onChange={this.setUser} id="username" required placeholder="User"></input>
        <label className="is-required">Password</label>
        <input  type="password"  name="password" onChange={this.setPass} id="password" required placeholder="Password"></input>
        <input  type="submit"  value="Log In"></input>
        <p>{this.state.message}</p>
      </form>
    )
  }
  });
  React.render(<APP />, document.getElementById('site'));

success 函数中的this与使用 $.ajax 启动请求时不同。你必须记住它并使用它,而不是以后this(在我的

handleForm:function(e){
      // ...
      // -->
      var self = this;
      // <--
      $.ajax({
         // ...
         success:function(result){
           if(result.error){
             // ...
           }
           else{
             // -->
             self.setErrors(result.message);
             // <--
           }
         },
         // ...
      });