为了账号安全,请及时绑定邮箱和手机立即绑定

使用 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 关注
  • 139 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信