【发布时间】:2020-05-12 00:40:21
【问题描述】:
现在真的受够了!我试图在 componentDidMount 函数中运行 3 个函数时显示 Spinner 元素。
从我收集到的渲染出现在 componentDidMount 之前,所以我在渲染中运行 Spinner,同时:
- 从 this.getValidToken() 中检索到一个 cookie 值
- 然后 axios 发布请求设置 isLoggedin 的状态(使用上述值作为有效负载)
- 然后 logic() 函数运行一个简单的 if 语句来登录用户或重定向到 错误页面。
我不断收到关于 Promises 的错误,我觉得有更好的方法来做到这一点?
constructor(props){
super(props);
this.state = {
isLoggedIn: false
}
}
componentDidMount() {
const post =
axios.post(//api post request here)
.then(function(response) {
this.setState({ isLoggedIn: true });
})
.catch(function(error) {
this.setState({ isLoggedIn: false });
})
const LoggedIn = this.state.isLoggedIn;
const logic = () => {
if (LoggedIn) {
//log user in
} else {
//redirect user to another page
}
};
this.getValidToken()
.then(post)
.then(logic);
//getValidToken firstly gets a cookie value which is then a payload for the post function
}
render() {
return <Spinner />;
}
【问题讨论】:
标签: reactjs post promise es6-promise