如何在reactjs中使用响应ajax请求设置状态

时间:2016-09-28 22:11:00

标签: javascript ajax reactjs

我绑定并使用它仍然得到这个错误,做了同样的事情 另外,当它在这里做同样的事情时它工作得很完美,但我收到了一个错误。

 class Player extends React.Component{
    constructor(){
        super();
        this.setState={
            video:{}
        };
    }

    componentDidMount () {
         var sess=localStorage.getItem('sessionId');
        var id=this.props.params.vid;
  

本地ajax请求控制台日志显示我的请求很好

    $.ajax({
      method:'GET',
       url:'video',
       data:{
         'sessionId':sess,
         'videoId':id
       },
       success:function(res){
         this.setState({ video:res.data })
       }.bind(this)
    });
  }
    render(){

        return(

            <div id="videoplay">
            <div className="video-title"></div>
              <video  controls src="/images/Google_Cardboard_Assembly.mp4">
            </video>
                <div className="video-metadata">

                    <div className="video-rating"></div>
                    <div className="video-description"></div>                    

                </div>
            </div>           
        );
    }

}

错误

Uncaught TypeError: this.setState is not a function

4 个答案:

答案 0 :(得分:1)

在构造函数中,您只需要执行function LoadNumbers(a, b) { var url = _spPageContextInfo.webAbsoluteUrl var call = $.ajax({ url: url + "/_api/Web/Lists/GetByTitle('xyz')/items?$select=1, 2,3 &$filter=(Num1 eq '" + VNum + "')and(Num2 eq '" + PNum + "')&$orderby=ID asc&$top=5000", type: "GET", dataType: "json", headers: { Accept: "application/json;odata=verbose" } }); call.done(function(data, textStatus, jqXHR) { $('#example').dataTable({ "bDestroy": true, "bProcessing": true, "aaData": data.d.results, "aoColumns": [{ "mData": "abc" }, { "mData": "xyz" }, { "mData": "pqr" }, ], dom: 'Bfrtip', buttons: [ 'excel', 'print' ] }); }); call.fail(function(jqXHR, textStatus, errorThrown) { alert("Error retrieving Tasks: " + jqXHR.responseText); }); }而不是this.state = { video: {} }

this.setState
除了构造函数之外,

constructor(){ super(); this.state = { video:{} }; } 可以在任何其他地方使用。非es6方式这样做:

this.setState

等同于在构造函数中执行getInitialState: function() { return { video: {} } }

答案 1 :(得分:1)

这是我如何运作

class Login extends Component{
 constructor(props){
 super(props);
 this.state={
  email:'',
  password:''
  emailError:'',
  passwordError:''
  }
  this.userLogin=this.userLogin.bind(this);
  this.handleUserInput=this.handleUserInput.bind(this);
 }

handleUserInput(){
 const name = e.target.name;
 const value = e.target.value;
 this.setState({[name]: value})
}

userLogin(){
var body={
  email:this.state.email,
  password:this.state.password
}
 $.ajax({
  type: 'POST',
  url: 'http://localhost:8080/userLogin',
  data: body,
  success:function(data){
      console.log(data);
      if(data==='valid'){
      window.location.href='/dashboard';
      }
      else{
      //setting error details here
      this.setState({emailError:'email doesn\'t exist', 
        passwordError:'incorrect password'});
      window.location.href='/';
      }
  }.bind(this),
  error:function(){
    console.log("error");
    this.setState({emailError:'email doesn\'t exist', 
    passwordError:'incorrect password'});
  }.bind(this)
});
}

render(){
return(
<div>
   <h2>Login:</h2>
  <form>
     <input type="text" placeholder="email" name="email" onChange={(event) 
       => this,handleUserInput(event)}/>
     <h6>{this.state.emailError}</h6>
     <input type="text" placeholder="email" name="email"  onChange={(event) 
       => this,handleUserInput(event)}/>
     <h6>{this.state.passwordError}</h6>
     <button onClick={this.userlogin}>Login</button>
  </form>
</div>
)
}
}

答案 2 :(得分:0)

您可以使用React生命周期方法发出请求。

实施例

class YourClass extends Component {
  constructor () {
    super();
    this.state = {
      video: {}
    };
  }

  componentDidMount () {
    $.ajax({
      method: 'GET',
      url: 'video',
      data: {
        sessionId: sess,
        videoId: id
      },
      success: (res) => {
        this.setState({ video:res.data })
      }
    });
  }

  render () {
    return ( /* ... your render method ... */ );
  }
}

答案 3 :(得分:0)

您需要修改构造函数方法:

constructor(){
    super();
    this.setState={
        video:{}
    };
}

为:

constructor(){
    super();
    this.state = {
        video:{}
    };
}

此外,我认为this来电中的this.setState()并未在$.ajax()来电中引用您的班级。尝试绑定:ajax()调用和success()函数,或使用success()方法的箭头函数。