React componentDidMount和Promises吗?

问题描述 投票:0回答:1

现在真的受够了!我正在尝试在componentDidMount函数中运行3个函数的同时显示Spinner元素。

根据我收集的渲染,在componentDidMount之前,所以我在渲染中运行Spinner,同时:

  1. 从this.getValidToken()中检索到一个cookie值
  2. 然后axios发布请求设置isLoggedin的状态(使用上面的值作为有效负载)
  3. 然后,逻辑()函数运行一个简单的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
1个回答
0
投票

首先,您将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 />;
}
© www.soinside.com 2019 - 2024. All rights reserved.