所以我有一個動作向一個端點發出 POST 請求,該端點為特定的藝術品創建評論。在渲染圖稿及其評論的組件上,我在 onMounted() 鉤子中分派一個動作,該操作對具有該 id 的圖稿發出 GET 請求,然后將其存盤在 Vuex 中。
創建評論的 POST 請求通過后,我可以訪問商店中的藝術作品屬性,并將回應推送到評論屬性,即評論陣列。我不知道這是否是正確的方法,因為據我所知,任何狀態更改都應該通過突變來完成,所以直接訪問狀態并將陣列元素推入其中似乎不正確?
這是我創建評論并將回應推送到所選藝術品的評論屬性的操作:
async createComment({commit, state}, payload){
try {
let response = await axios.post("/createComment", payload)
console.log(response)
state.image.comments.push(response.data.comment)
} catch (error) {
console.log(error)
}
},
我想另一種方法是從 state 復制藝術品,在副本的 comments 屬性中推送新評論,然后提交新物件?
uj5u.com熱心網友回復:
從狀態中獲取物件并改變其屬性違反了所有更改的“單一來源”原則,這就是您首先使用存盤的原因。
您必須將狀態中的物件替換為自身的修改版本。在您的情況下,以下是突變的樣子:
this.$store.commit('ADD_COMMENT', comment);
// in store:
mutations: {
ADD_COMMENT(state, comment) {
state.image = {
...state.image,
comments: [ ...(state.image.comments || []), comment]
}
}
}
這也可以通過push將注釋添加到現有comments陣列中來實作。但你仍然必須更換state.image:
// ? WRONG, you're not replacing the image:
state.image.comments.push(coment);
// ? CORRECT, you're replacing the image:
const clone = { ...state.image };
clone.comments.push(comment);
state.image = clone;
// that's why most prefer the spread syntax,
// to assign in one line, without using a const:
// state.image = { ...state.image, [yourKey]: yourNewValue };
重要提示:變異狀態應該只發生在變異函式內部。如果它發生在外面,Vue 會警告你。有時它可能會起作用(例如,您實際上可能會看到組件中的更改并且它可能會正確呈現),但不能保證它會起作用。
更新狀態陣列中的物件的示例:
如果影像是存盤到 state 中的陣列的一部分,(比如images),并且考慮到每個影像都有一個唯一的 identifier id,那么你可以這樣做:
this.$store.commit('ADD_IMAGE_COMMENT', { id: image.id, comment });
// the mutation:
mutations: {
ADD_IMAGE_COMMENT(state, { id, comment }) {
const index = state.images.findIndex(image => image.id === id);
if (index > -1) {
state.images.splice(index, 1, {
...state.images[index],
comments: [...(state.images[index].comments || []), comment]
});
}
}
}
上述突變改變了images陣列,有效地用其自身的新副本替換它,其中包含所有其他未修改的影像以及與舊影像索引相同的修改影像的新版本。修改后的影像包含舊影像包含的所有內容,除了評論陣列,被一個新陣列替換,包含舊影像的所有內容以及新評論。
uj5u.com熱心網友回復:
您可以創建突變:
const mutations = {
addComment(state, comment) {
state.image = {
...state.image,
comments: [ ...state.image.comments, comment]
}
},
},
然后從您的操作中提交:
async createComment({commit, state}, payload){
try {
let response = await axios.post("/createComment", payload)
console.log(response)
commit('addComment', response.data.comment);
} catch (error) {
console.log(error)
}
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/378488.html
