Vuex,在动作中改变状态
Vuex, changing state in an action
在学习 Vuex 的过程中,我正在尝试尽可能 "good practice" 编码。
据我所知,我认为 Actions 用于执行外部 API 调用,其结果将传递给 Mutation 通过 commit()。
Now I want to increment a counter for a certain user on Firebase. This is working when I code my action like this
ADD_CREDIT(context, user) {
user.credits++;
firebase.database().ref('users').child(user.id)
.update({credits: user.credits})
.then(() => {});
}
所以在我的操作中,我已经在调用 API 调用之前更新了状态。这是好习惯吗?我用下面的代码尝试了另一种方法,但这看起来很复杂..而且现在不起作用。
动作
ADD_CREDIT({commit, state}, user) {
const newcredits = user.credits + 1;
firebase.database().ref('users').child(user.id)
.update({credits: newcredits})
.then(() => {
commit('CREDIT_CHANGED', user.id, newcredits)
});
}
变异
CREDIT_CHANGED(state, userid, newcredits) {
let user = state.users.find(user => {
return user.id = userid
});
user.credits = newcredits;
}
突变函数的模式是
function mutation(state, payload) {
...
// do something with state
state.person = payload;
...
}
它没有比 2 更多的参数了。
因此,您的突变应该传递一个包含您所有信息的对象。像这样:
CREDIT_CHANGED(state, payload) {
let user = state.users.find(user => user.id === payload.userid);
user.credits = payload.newcredits;
}
然后你的动作应该像这样提交:
ADD_CREDIT({commit, state}, user) {
const newcredits = user.credits + 1;
firebase.database().ref('users').child(user.id)
.update({credits: newcredits})
.then(() => {
commit('CREDIT_CHANGED', {
userid: user.id,
newcredits: newcredits
})
});
}
在学习 Vuex 的过程中,我正在尝试尽可能 "good practice" 编码。
据我所知,我认为 Actions 用于执行外部 API 调用,其结果将传递给 Mutation 通过 commit()。
Now I want to increment a counter for a certain user on Firebase. This is working when I code my action like this
ADD_CREDIT(context, user) {
user.credits++;
firebase.database().ref('users').child(user.id)
.update({credits: user.credits})
.then(() => {});
}
所以在我的操作中,我已经在调用 API 调用之前更新了状态。这是好习惯吗?我用下面的代码尝试了另一种方法,但这看起来很复杂..而且现在不起作用。
动作
ADD_CREDIT({commit, state}, user) {
const newcredits = user.credits + 1;
firebase.database().ref('users').child(user.id)
.update({credits: newcredits})
.then(() => {
commit('CREDIT_CHANGED', user.id, newcredits)
});
}
变异
CREDIT_CHANGED(state, userid, newcredits) {
let user = state.users.find(user => {
return user.id = userid
});
user.credits = newcredits;
}
突变函数的模式是
function mutation(state, payload) {
...
// do something with state
state.person = payload;
...
}
它没有比 2 更多的参数了。
因此,您的突变应该传递一个包含您所有信息的对象。像这样:
CREDIT_CHANGED(state, payload) {
let user = state.users.find(user => user.id === payload.userid);
user.credits = payload.newcredits;
}
然后你的动作应该像这样提交:
ADD_CREDIT({commit, state}, user) {
const newcredits = user.credits + 1;
firebase.database().ref('users').child(user.id)
.update({credits: newcredits})
.then(() => {
commit('CREDIT_CHANGED', {
userid: user.id,
newcredits: newcredits
})
});
}