【问题标题】:Cannot get store states with getters in Vuex with promise then无法在 Vuex 中使用 getter 获取商店状态,然后承诺
【发布时间】:2021-04-27 12:16:45
【问题描述】:

由于我想检查他们输入的频道路由是否需要 PIN 码,我使用 router.beforeEach 如下:

router.beforeEach((to, from, next) => {  
  if(to.path == '/') {
    next();
  }else {                
    store.dispatch('checkChannelhasPin', to.params.id).then(()=>{
    console.log(store.getters);
    console.log(store.getters.ispin);
    setTimeout(() => {
      console.log(store.getters.ispin);
     }, 500);
   }) 
  }
}

作为console.log,我得到了三个结果:

问题是,我在检查 'checkChannelhasPin' 后无法获取 stateispin。

动作:

import axios from 'axios';
import setChannelAuthToken from '../../utils/setChannelAuthToken';
import {
  CHECK_CHANNEL_HASPIN
} from '../typeName';

const state = {
  ispin: true,      
}

const getters = {  
  ispin: (state) => state.ispin
};

const actions = {      
  async checkChannelhasPin({commit}, params) {    
    axios.post(
      window.home+'/json/channel/checkAuth',
      {
        channel_id:params
      }
    ).then((response) => {      
      let payload = response.data.ispin;
      commit(CHECK_CHANNEL_HASPIN, payload); 
    }).catch( (error) => {
      console.log(error);
    });
  }
}


const mutations = {
  CHECK_CHANNEL_HASPIN: (state, payload) => (state.ispin = payload)
};

export default {
  state,
  getters,
  actions,
  mutations
};

你能推荐我吗?非常感谢。

【问题讨论】:

  • @Dan 我更新了动作,你能检查一下吗?作为redux of React,状态将在操作完成后动态更新,但我无法使用 vuex。有什么不同?

标签: javascript vue.js promise async-await vuex


【解决方案1】:

您需要从操作中返回承诺:

checkChannelhasPin({commit}, params) {    
  return axios.post(
    window.home+'/json/channel/checkAuth',
    {
      channel_id:params
    }
  ).then((response) => {      
    let payload = response.data.ispin;
    commit(CHECK_CHANNEL_HASPIN, payload); 
  }).catch( (error) => {
    console.log(error);
  });
}

或者,如果您使用 async/await 语法,您可以这样做:

async checkChannelhasPin({commit}, params) {
  try {
    const response = await axios.post(
      window.home+'/json/channel/checkAuth',
      {
        channel_id:params
      }
    )
    let payload = response.data.ispin;
    commit(CHECK_CHANNEL_HASPIN, payload); 
  } catch(error) {
    console.log(error);
  }
}

当您使用.then 时,您必须明确返回承诺。当您使用async/await 时,您不会。您使用的是 async 关键字,但使用的是 .then 而不是 await

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-21
    • 2017-04-28
    • 2021-04-10
    相关资源
    最近更新 更多