【发布时间】:2019-03-31 02:37:50
【问题描述】:
从 axios 获取请求得到响应后,我无法更改状态
这是一个使用 MERN 堆栈的简单登录/注册页面,只有在 node.js 后端授权他之后,我才尝试访问用户个性化页面。 我已经尝试了使用 _ismounted 常见的方法,但是经过一些调试后,我看到 componentWillMount 方法在 axios get 之后立即被调用,然后将 _isMounted 设置为 false,因此不会进入我使用 setState 的 if 代码中
class User extends Component {
_isMounted = false;
constructor(props){
super(props)
this.state={
isAuthenticated:false
}
}
componentDidMount(){
this._isMounted = true;
const token=localStorage.getItem("token");
//alert(token);
axios
.get(`https://localhost:3443/users/${this.props.user}`,{ headers: { Authorization: `Bearer ${token}` } })
.then(res => {
if (this._isMounted){
this.setState(() => ({
isAuthenticated:true
}));
}
})
.catch(err => alert(JSON.stringify(err)));
}
componentWillUnmount() {
this._isMounted = false;
}
render() {
if(this.state.isAuthenticated===false) return(<Redirect to="/home" />)
return(
<div>
Hello {this.props.user}
</div>
);
}
}
我只想在页面呈现之前执行 axios get 以检查用户是否被授权并相应地更改状态。
【问题讨论】: