亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 SSR 時,Nuxt Store 的初始狀態未定義

使用 SSR 時,Nuxt Store 的初始狀態未定義

躍然一笑 2023-04-14 17:17:22
我為我的索引頁面創建了一個 Nuxt 存儲,目的是初始化狀態并從 API 獲取一些數據以改變狀態。這是我商店的代碼,包括初始狀態、突變和操作。import Axios from "axios";//a controller has a store that it interfaces with// set initial state of the storeconst initState = () => ({  message: "init"})// make the state usable from other componentsexport const state = initState//when you need to change the state//for mutations you do commitsexport const mutations = {  setMessage(state, message) {    state.message = message  }, //can define more functions here  reset(state) {    Object.assign(state, initState())  }}//when you have to do API calls (async)//commit parameter allows us to invoke the mutation functions//for actions you do dispatchexport const actions = {    async nuxtServerInit({commit}) {      const message = await Axios.get("http://localhost:5000/api/home").data;      console.log(message);      commit("setMessage", message) //put name of mutation as parameter + payload    }}在我的 index.vue 文件中,我從 vuex 導入所需的函數并映射狀態。import Logo from '~/components/Logo.vue'import VuetifyLogo from '~/components/VuetifyLogo.vue'import Axios from "axios";import {mapState, mapActions, mapMutations} from 'vuex'export default {  components: {    Logo,    VuetifyLogo  },  computed: mapState({    message: state => state.message  }),  methods: mapMutations([    "reset",    "setMessage"  ])但是,當我加載頁面(使用 Vue 開發工具)時,我的狀態開始未定義。我可以通過“重置”方法改變狀態,但我的 API 沒有被調用來獲取數據。我在控制臺中沒有收到任何錯誤,所以我不確定是什么原因造成的。我的 API 也已啟動并正在運行。如何確保在加載頁面時調用 nuxtServerInit 操作?
查看完整描述

1 回答

?
MMMHUHU

TA貢獻1834條經驗 獲得超8個贊

我相信這個nuxtServerInit動作被恰當地調用了。我敢打賭,它message的值始終為未定義,因為 Axios.get("http://localhost:5000/api/home")返回的 promise 沒有屬性data。您必須先等待結果,然后獲取它的數據。


// note extra parentheses

const message = await (Axios.get("http://localhost:5000/api/home")).data;

此外,您可能希望將 axios 調用包裝在 try-catch 中,否則如果調用失敗,您將獲得帶有堆棧跟蹤的默認 Nuxt 錯誤頁面。


  async nuxtServerInit ({ commit }: any) {

    try {

      const message = (await Axios.get('http://localhost:5000/api/home')).data;

      console.log(message);

      commit('setMessage', message); // put name of mutation as parameter + payload

    } catch (error) {

      // you could redirect to custom error page for instance

      console.error(error);

    }

  }


查看完整回答
反對 回復 2023-04-14
  • 1 回答
  • 0 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號