我在 vuex 操作中有一個方法可以呼叫 api 并更新用戶資訊。我想要做的是將 axios 呼叫移動到它自己的方法中并且沒有任何運氣。
這是我的代碼
async updateProfile({ commit, dispatch }: any, user: User):Promise<User> {
console.log(user)
console.log("currentUser")
const response = await axios.request({
method: "PUT",
url: `/users/me/profile`,
data: user
});
// dispatch('updateUserProfile', user);
console.log(response)
console.log("response")
return user;
// return response;
},
async updateUserProfile(user: any): Promise<User> {
return await axios.request({
method: "PUT",
url: `/users/me/profile`,
data: user
});
},
注釋掉 dispatch 的行試圖呼叫 axios 方法并將用戶作為引數傳遞。當我嘗試該行而不是 axios.request 時,我收到 400 錯誤。當我將 user: any 更改為 user: User 我得到一個 Types of property 'actions' is incompatible。錯誤
uj5u.com熱心網友回復:
你的網址不一樣。一個有前導斜線,另一個沒有。你的第二個動作應該{}作為第一個引數。應該是async updateUserProfile({}, user: any)。這可能解釋了為什么您得到 400。您的請求有效負載可能是空的,不是嗎?
uj5u.com熱心網友回復:
您是否將updateProfile和都定義updateUserProfile為 vuex 操作?如果是這樣,后者看起來根本不像是一個動作;所有動作的第一個引數是context。
讓它成為一個獨立的功能,與你的商店完全分開
// could even be in another file / module entirely
const updateUserProfile = (user: User) =>
axios.put<User>("/users/me/profile", user)
從一個動作中,你可以直接呼叫它
// S = state type, R = root state type
async yourAction({ commit }: ActionContext<S, R>, user: User): Promise<User> {
const response = await updateUserProfile(user)
// here's where you would commit something
return user // or whatever
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/369880.html
下一篇:獲取工會成員的型別
