React:如何在 get 请求中设置状态?
React: how do I set a state inside a get request?
所以我有一个导航栏,如果用户已登录,我希望它显示用户名,如果声明:
var that= this;
this.state = {name: null, signedIn: false}
if (user){
axios.get('https://apiendpoint/' + user.id)
.then(function (response) {
console.log(response);
that.state = {name: response.data.firstName, signedIn: true}
//this.setState({ showModal: false });
})
.catch(function (error) {
console.log(error);
});
}
if 语句是 运行,但似乎没有设置状态变量。 var that =this
无法设置状态变量还是有更好的方法?
想通了。我不得不使用 that.setState({...});
而不是 this.state = {...}
所以我有一个导航栏,如果用户已登录,我希望它显示用户名,如果声明:
var that= this;
this.state = {name: null, signedIn: false}
if (user){
axios.get('https://apiendpoint/' + user.id)
.then(function (response) {
console.log(response);
that.state = {name: response.data.firstName, signedIn: true}
//this.setState({ showModal: false });
})
.catch(function (error) {
console.log(error);
});
}
if 语句是 运行,但似乎没有设置状态变量。 var that =this
无法设置状态变量还是有更好的方法?
想通了。我不得不使用 that.setState({...});
而不是 this.state = {...}