简体   繁体   中英

how to set state with reponse ajax request in reactjs

I bind and used this still getting this error ,did the same thing for another it worked perfect when did the same here, But I'm getting a error.

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

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

local ajax request console log shows my request is good

    $.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>           
        );
    }

}

error

Uncaught TypeError: this.setState is not a function

here is how i got it work

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>
)
}
}

in the constructor, you just need to do this.state = { video: {} } not this.setState

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

this.setState can be used anywhere else but the constructor. non es6 way of doing this was doing:

getInitialState: function() {
  return { 
    video: {}
  }
}

which is equivalent to just doing this.state = {} in the constructor

You can use the React lifecycle methods to make your request.

Example

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 ... */ );
  }
}

You need to modify your constructor method from:

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

to:

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

Also, I think this in this.setState() call does not refer to your Class in $.ajax() call. Try binding both: the ajax() call and the success() function or use the arrow function for your success() method.

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