2017-05-31 181 views
0

我的登录组件出现问题,我使用的是cointainer模式,所以我有一个组件登录管理api调用和一个管理输入并警告用户的DumbLogin关于我的服务器的响应。 我正在使用Axios来做api调用,它使用承诺来做到这一点,我也使用箭头函数来避免这个问题,那是我在想什么...... 因为最后我有React Axios在setState后没有渲染

TypeError: _this.setState is not a function

我试图用一个变量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', 
      }); 
     }); 

(自旋是布尔通知DumbLogin它应该或不显示一个微调在等待我的服务器响应)

回答

0

这是因为匿名函数内的thisthen内是而不是React组件的this

您需要为正在调用ajax的函数绑定正确的this(Reac Component's this)。

例如。如果函数是:

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

你可以在构造其绑定:

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

无论其!

这是不推荐的解决方案,你通常会不想要做的Ajax调用的组件......你可能想终极版,mobx甚至是终极版,传奇为此,

+0

我不知道这事, 谢啦! 我用thunk结束了:) – Darakt