我绑定(bind)并使用它仍然得到这个错误,做了同样的事情 另一个在此处执行相同操作时效果很好,但我遇到了错误。
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>
);
}
}
错误
Uncaught TypeError: this.setState is not a function
最佳答案
我是这样实现的
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>
)
}
}
关于javascript - 如何在 reactjs 中使用响应 ajax 请求设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39758482/