【发布时间】:2019-05-08 00:40:21
【问题描述】:
我在两个地方使用 axios 返回的承诺时遇到了一些困难。我想在我的 Vuex 操作中使用 .then() 来提交对我的状态的更改,返回 axios 承诺并在我的组件中再次使用 .then() 来更新 UI。我遇到的问题是我的组件内部未定义承诺响应。
// component
methods: {
getUser(userId) {
this.$store.dispatch('GET_USER', userId)
.then(response => {
console.log(response); // undefined
});
}
}
// vuex
actions: {
GET_USER: ({commit}, userId) => {
return api.getUserById(userId)
.then(({data}) => {
commit('ADD_USER', data);
});
}
}
// api service
getUserById(userId) {
return axios.get('/api/users/' + userId);
}
如果我在我的 Vuex 操作中删除 .then() 的使用,response 将成为我的 api 中的对象,但我想在我的组件中有一个承诺,以便我可以 catch 错误。
// component
methods: {
getUser(userId) {
this.$store.dispatch('GET_USER', userId)
.then(response => {
console.log(response); // no longer undefined
});
}
}
// vuex
actions: {
GET_USER: ({commit}, userId) => {
return api.getUserById(userId); // removed 'then' method
}
}
第一个代码块有什么问题?
谢谢。
【问题讨论】:
-
在第一个块中,您的
then不返回任何内容(因此返回undefined) -
@Vivick 从第一个
then内部返回data有效。谢谢你。欢迎您写一个答案,这样您就可以获得代表。
标签: javascript vue.js vuex