为什么重新加载会在一半时间内返回空状态?

时间:2019-03-27 11:40:43

标签: javascript vue.js vuex nuxt

我正在为Nuxt 2.5中的一个业余项目创建一个网上商店。在Vuex商店中,我有一个状态为“ currentCart”的模块。在这里,我存储了一个具有ID和产品数组的对象。我从后端获得具有ID的购物车,该ID存储在cookie中(带有js-cookie)。

我使用nuxtServerInit从后端获取购物车。然后我将其存储在状态中。然后在组件中,我尝试获取状态并显示购物车中的商品数,如果购物车为空,则显示“ 0”。这给出了奇怪的结果。一半的时间正确地说出有多少产品,但是Vuex开发工具告诉我购物车为空。另一半时间显示为“ 0”。

起初,我有一个中间件,该中间件在商店中触发设置购物车的操作。这根本无法始终如一地工作。然后,我尝试使用nuxtServerInit设置商店,这实际上是正确的。显然我更改了一些内容,因为今天它给出了已描述的问题。我不知道为什么会产生这个问题。

nuxtServerInit:

nuxtServerInit ({ commit }, { req }) {
  let cartCookie;

  // Check if there's a cookie available
  if(req.headers.cookie) {

    cartCookie = req.headers.cookie
    .split(";")
    .find(c => c.trim().startsWith("Cart="));

    // Check if there's a cookie for the cart
    if(cartCookie)
      cartCookie = cartCookie.split("=");
    else
      cartCookie = null;
  }
  // Check if the cart cookie is set
  if(cartCookie) {

    // Check if the cart cookie isn't empty
    if(cartCookie[1] != 'undefined') {
      let cartId = cartCookie[1];

      // Get the cart from the backend
      this.$axios.get(`${api}/${cartId}`)
      .then((response) => {
        let cart = response.data;
        // Set the cart in the state
        commit("cart/setCart", cart);
      });
    }
  }
  else {
    // Clear the cart in the state
    commit("cart/clearCart");
  }
},

突变:

setCart(state, cart) {
  state.currentCart = cart;
}

吸气剂:

currentCart(state) {
  return state.currentCart;
}

在cart.vue中:

if(this.$store.getters['cart/currentCart'])
  return this.$store.getters['cart/currentCart'].products.length;
else
  return 0;

状态对象:

const state = () => ({
  currentCart: null,
});

我将console.logs放在各处,以检查哪里出错了。 nuxtServerInit有效,提交“ cart / setCart”启动并具有正确的内容。在吸气剂中,大多数时候我都为空。如果我在另一次重新加载后快速重新加载页面,则我在getter中获得了正确的购物车,并且组件获得了正确的计数。 Vue开发人员工具说,即使组件显示了我期望的数据,currentCart状态也为空。

我将状态对象更改为“ currentCart:{}”,现在大部分时间都可以使用,但是每3/4重载它都会返回一个空对象。因此,很显然,getter在状态设置之前触发,而状态是由nuxtServerInit设置的。那正确吗?如果是这样,那是为什么?我该如何更改?

我不了解什么?我完全感到困惑。

1 个答案:

答案 0 :(得分:1)

所以,您知道当您输入问题以在Stackoverflow上提问时,提交后有一些新想法可以尝试吗?这就是其中之一。

我编辑了一个问题,告诉我何时将状态对象更改为空对象,有时它返回一个空对象。然后打到我了,吸气剂有时在nuxtServerInit之前触发。在文档中指出:

  

注意:异步nuxtServerInit操作必须返回Promise或利用async / await来允许nuxt服务器等待它们。

我将nuxtServerInit更改为此:

async nuxtServerInit ({ commit }, { req }) {
  ...
  await this.$axios.get(`${api}/${cartId}`)
  .then((response) => {
    ...
  }
  await commit("cart/clearCart");

所以现在Nuxt可以等待结果了。开发工具仍然显示为空状态,但是我认为这是一个错误,因为我可以在应用程序的其余部分中很好地使用存储状态。