【问题标题】:React componentDidMount and working with Promises?React componentDidMount 并使用 Promises?
【发布时间】:2020-05-12 00:40:21
【问题描述】:

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

从我收集到的渲染出现在 componentDidMount 之前,所以我在渲染中运行 Spinner,同时:

  1. 从 this.getValidToken() 中检索到一个 cookie 值
  2. 然后 axios 发布请求设置 isLoggedin 的状态(使用上述值作为有效负载)
  3. 然后 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


    【解决方案1】:

    首先,您将 axios post 分配给一个变量,它会立即执行,而不是在 getValidToken 承诺被解决后执行

    其次,react 中的状态更新是异步的,因此您不能基于 promise 解析器中的状态来登录逻辑

    您可以处理上述情况

    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 />;
    }
    

    【讨论】:

    • 啊,太棒了,谢谢@Shubham,现在正在尝试更改,现在非常有意义!
    猜你喜欢
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 2020-02-12
    相关资源
    最近更新 更多