【问题标题】:I can't get the js response in variable that say is null我无法在变量中获得 js 响应,说是 null
【发布时间】:2019-11-09 13:34:29
【问题描述】:

当我在 get 方法中连接 axion 时,我从我的 api 得到响应,我想在网站上打印信息。

我试图改变这一行:

 .then(response => (this.username= response.data.username)) or this
 .then(response => (this.username= response.data[0].username)) or this 
 .then(response => (this.username= response.data.username[0]))

脚本

<script>
   import axios from 'axios';

   export default {
     name: "acount",
     el: '#app',
     data() {
       return {
         username: null,
         pseudo: null,
         email: null,
         date: null,
       };
   },
   mounted () {
     axios
      .get('http://127.0.0.1:8080/api/user/65', {
      headers: {
      token: ''
      }
  })
    .then(response => (this.username= response.data[0].username[0]))
    .then(response => (this.pseudo = response.data.pseudo))
    .then(response => (this.email = response.data.email))
    .then(response => (this.date = response.data.create_at))
  }
}
</script>

【问题讨论】:

标签: laravel api vue.js axios


【解决方案1】:

此箭头函数使用隐式返回值:

.then(response => (this.username= response.data[0].username[0]))

这导致下一个then 中的response 参数等于this.username。为避免此类错误,可以使用 ESLint no-return-assign 规则。

相反,它应该是:

.then(response => {
  this.username= response.data[0].username[0];
  return response;
})

多个then 是不必要的,因为没有多个要链接的承诺。它们可以重写为单个then

 axios.get(...)
    .then(response => {
        this.username= response.data[0].username[0]);
        ...
    });

【讨论】:

    【解决方案2】:

    为了链接 promise,then() 中的每个函数都需要返回一个值。除此之外,我们只能提供帮助,前提是我们知道实际响应的样子。

    new Promise(function(resolve, reject) {
    
      setTimeout(() => resolve(1), 1000); // (*)
    
    }).then(function(result) { // (**)
    
      alert(result); // 1
      return result * 2;
    
    }).then(function(result) { // (***)
    
      alert(result); // 2
      return result * 2;
    
    }).then(function(result) {
    
      alert(result); // 4
      return result * 2;
    
    });

    【讨论】:

      猜你喜欢
      • 2021-02-25
      • 1970-01-01
      • 2014-05-02
      • 2017-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-20
      相关资源
      最近更新 更多