對于我的專案,我使用的是 Nuxt。在商店的行動中,我有這段代碼:
async nuxtServerInit({ commit }) {
this.dispatch('fetchAllClients')
},
async fetchAllClients({ commit, state }) {
console.log('fetch clients')
await fetch('http://localhost:1337/api/clients', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then((res) => res.json())
.then((res) => commit('storeClients', res))
},
因此,在 Nuxt init 上,我希望運行一些 fetches,以便它可以更新一些狀態(這是在 destoreClients()中完成的,在 fetch 中提交)。如果我復制fetchAllClients()里面的方法,nuxtServerInit()那么一切都很好。
async nuxtServerInit({ commit }) {
await fetch('http://localhost:1337/api/clients', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then((res) => res.json())
.then((res) => commit('storeClients', res))
},
但是當我呼叫一個單獨的方法時,如上面的代碼所示,那么 fetch 將不起作用。顯示日志,因此該方法被正確呼叫。但不知何故, fetch 沒有做任何事情。我究竟做錯了什么?
uj5u.com熱心網友回復:
你應該有這個
async nuxtServerInit({ dispatch }) {
await dispatch('fetchAllClients')
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/473053.html
