【问题标题】:why axios return promise error in reactjs为什么axios在reactjs中返回promise错误
【发布时间】:2018-11-01 22:57:07
【问题描述】:

每次点击登录按钮时都会出错

TypeError: Cannot read property 'then' of undefined

,但重新加载后错误消失了。我能知道发生了什么吗?这是我的登录代码

onSignIn(e){
    e.preventDefault()

    this.Auth.login(this.state.signInUsername, this.state.signInPassword)
      .then(res => {
        this.props.history.replace('/')
      })
      .catch(err => {
        alert(err)
      })
  }

这是我的授权码:

login(username, password){
    axios.post('http://localhost:3000/user/login', {
      username,
      password
    })
    .then(this._checkStatus)
    .then(res => {
      if(res.data.success === true){
        const payload = {
          name: username,
        }
        this.setToken(payload)
        return Promise.resolve(res)
      }else{
        console.log(res.data.message)
      }
    })
    .catch(err => {
      return Promise.reject(err)
    })
  }

【问题讨论】:

  • .catch(err => { return Promise.reject(err) }) 是多余的,放弃吧。

标签: reactjs function promise axios request-promise


【解决方案1】:

从登录函数返回 axios。

login(username, password){
    return axios.post('http://localhost:3000/user/login', {
      username,
      password
    })
    .then(this._checkStatus)
    .then(res => {
      if(res.data.success === true){
        const payload = {
          name: username,
        }
        this.setToken(payload)
        return res;
      }else{
        console.log(res.data.message)
      }
    })
    .catch(err => {
      throw err;
    })
  }

【讨论】:

  • 使用您的代码后,此操作不起作用 this.props.history.replace('/')
  • 还是不行,我必须重新加载页面然后才能重定向
  • 我使用了 window.location.href = '/' 并且正在工作,但不知道这是否是最好的方法。
【解决方案2】:

我相信你的 axios.post 有 -two- ".then"。axios 网站提供的示例使用

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

每个 axios 调用只有一个 .then。

【讨论】:

    猜你喜欢
    • 2020-07-25
    • 2021-12-13
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 2016-12-27
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    相关资源
    最近更新 更多