【问题标题】:How to pass axios response to function argument?如何将 axios 响应传递给函数参数?
【发布时间】:2019-08-06 03:08:52
【问题描述】:

获取用户数据的过程如下,将用户的post数据存储在对象中。
还试图将帖子的第一条评论存储在帖子对象中。

getLatestCommentData(dataList) {
  if (dataList.length === 0) {
    return {}
  } else {
    return {
      body: dataList[0].body,
      created_at: dataList[0].created_at
    }
  }
},

async fetchUserInfo({ commit, dispatch }, { userId }) {
  const user = await this.$axios.$get(`/users/${userId}`)
  await Promise.all([
    this.$axios.$get(`users/${userId}/posts`).then(async posts => {
      user.posts = await Promise.all(
        posts.map(async post => ({
          ...post,
          latestComment: await dispatch(
            'getLatestCommentData',
            this.$axios.$get(`/posts/${post.id}/comment`)
          )
        }))
      )
    })
  ]).then(() => {
    commit('setUserInfo', user)
  })
},

但是,在上述代码的情况下,getLatestCommentDatadataList参数的内容如下,并不能正常工作。

{ dispatch: [Function],
  commit: [Function],
  getters: { mainUser: [Getter] },
  state: { mainUser: {} },
  rootGetters: { .... },
  rootState:{ .... } },

如何将 axios 响应数据传递给dataList

【问题讨论】:

标签: javascript vue.js async-await axios nuxt.js


【解决方案1】:

像函数一样使用 getLatestCommentData。声明它:

function getLatestCommentData(dataList) {
  if (dataList.length === 0) {
    return {}
  } else {
    return {
      body: dataList[0].body,
      created_at: dataList[0].created_at
    }
  }
}

稍后在某处使用它:


posts.map(async (post) => ({
  ...post,
  latestComment: getLatestCommentData(await this.$axios.$get(`/posts/${post.id}/comment`))
  })
);

【讨论】:

    猜你喜欢
    • 2021-08-11
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 2019-06-23
    • 1970-01-01
    • 2018-08-14
    相关资源
    最近更新 更多