【问题标题】:React Axios not rendering after setState在 setState 之后 React Axios 不渲染
【发布时间】:2017-11-01 12:12:49
【问题描述】:

我的 Login 组件有问题,我正在使用 cointainer 模式,所以我有一个组件 Login 来管理 api 调用和 DumbLogin 管理输入并警告用户我的服务器的响应. 我正在使用 Axios 进行 api 调用,它使用承诺来做到这一点,我还使用箭头函数来避免与 this 相关的麻烦,这就是我的想法...... 因为最后我有

TypeError: _this.setState 不是函数

我尝试使用变量 self 来解决该问题,但导致同样的错误。

我应该怎么做?

axios(all)
        .then((response) => {
        console.log(response);
            if (response.status === 200){
                this.setState({
                    ...this.state,
                    spin: false,
                });
                let data = response.data;
                this.props.connect(data.username, data.email, data.token, data.partners);
                this.props.router.push('panel');
            }
        }).catch((error) => {
            console.log(error.response);
            this.setState({
                spin: false,
                errorLogin: 'Username or password wrong',
            });
        });

(spin 是一个布尔值,用于通知 DumbLogin 在等待我的服务器响应时是否应该显示微调器)

【问题讨论】:

    标签: reactjs promise axios arrow-functions setstate


    【解决方案1】:

    这是因为then内部匿名函数内部的this不是React组件的this。

    您需要为执行 ajax 调用的函数绑定正确的 this(Reac 组件的 this)。

    例如。如果函数是:

    fetchData(){
        axios(all).then(...).catch(...)
    }
    

    你可以在构造函数中绑定它:

    constructor(){
       this.fetchData = this.fetchData.bind(this)
    }
    

    但是!

    这不是推荐的解决方案,您通常不想在组件中进行 ajax 调用...您可能需要 redux、mobx 甚至 redux-saga 来实现此目的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 2018-07-17
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      相关资源
      最近更新 更多