我正在尝试将登录页面重定向到成员页面,因为它从其他服务检索了身份验证:
这是我的登录组件:
onclick="platformSelect(1);"
onclick='platformSelect(1);"
onclick='platformSelect(1)'
但是当fetch函数返回并且我从Authorization标头获取数据时,我无法调用this.setState(),因为它抛出:
class Login extends Component {
state = {
credentials:{
"username": "",
"password": ""
},
clientToken: ""
}
constructor(props){
super(props);
this.handleUsernameChange = this.handleUsernameChange.bind(this);
this.handlePasswordChange = this.handlePasswordChange.bind(this);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
}
handleUsernameChange(event){
this.state.credentials.username = event.target.value;
}
handlePasswordChange(event){
this.state.credentials.password = event.target.value;
}
handleFormSubmit(event){
event.preventDefault();
const data = JSON.stringify(this.state.credentials);
fetch(loginFormurl, {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: data,
})
.then(function(response){
if(response.ok){
console.log(response.headers.get('Authorization'));
this.setState({clientToken: response.headers.get('Authorization')});
}else{
console.log(response.statusText);
}
})
.catch(function(error) {
console.log(error);
});
}
render() {
if (this.state.clientToken !== "") {
return <Redirect to='./members' />;
}
return (
<div className="App">
<h1 className="Login-title">Login to Social Media Aggregator</h1>
<form className="Login-box" onSubmit={this.handleFormSubmit}>
<p>
<label>
Username
<input id="username" type="text" name="username" required onChange={this.handleUsernameChange}/>
</label>
</p>
<p>
<label>
Password
<input id="password" type="password" name="password" autoComplete="password" required onChange={this.handlePasswordChange}/>
</label>
</p>
<p><input type="submit" value="Login"/></p>
</form>
</div>
);
}
}
export default withRouter(Login);
有关如何解决此问题的任何建议? 谢谢!
答案 0 :(得分:2)
这是因为this
解析为您创建的匿名函数(Object):
.then(function(response){ // you create a function/Object
if(response.ok){
console.log(response.headers.get('Authorization'));
this.setState({clientToken: response.headers.get('Authorization')}); // `this` is the anonymous function not React component
}else{
console.log(response.statusText);
}
})
出于同样的原因,你在构造函数中有bind
个ed类函数。
如果你可以使用箭头功能,这种方式this
将使用使用箭头功能的上下文 - 这将是你的登录组件:
.then((response) => { // you create a function/Object
if(response.ok){
console.log(response.headers.get('Authorization'));
this.setState({clientToken: response.headers.get('Authorization')}); // `this` is the anonymous function not React component
}else{
console.log(response.statusText);
}
})