现在真的受够了!我正在尝试在componentDidMount函数中运行3个函数的同时显示Spinner元素。
根据我收集的渲染,在componentDidMount之前,所以我在渲染中运行Spinner,同时:
我不断收到有关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 />;
}
首先,您将axios帖子分配给变量,它会立即执行,而不是在getValidToken承诺被撤销后才执行
第二,react中的状态更新是异步的,因此您不能基于promise解析器中的状态进行loginIn逻辑]
您可以通过类似的方式处理以上情况
constructor(props){
super(props);
this.state = {
isLoggedIn: false
}
}
componentDidMount() {
const post = () => axios.post(//api post request here)
.then(function(response) {
this.setState({ isLoggedIn: true });
return true;
})
.catch(function(error) {
this.setState({ isLoggedIn: false });
return false;
})
const logic = (isLoggedIn) => { // use promise chaining here
if (isLoggedIn) {
//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 />;
}