javascript - 无法在 Vuex 中使用 getter 获取商店状态,然后承诺
问题描述
由于我想检查他们输入的通道路由是否需要 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
};
你能建议我吗?非常感谢。
解决方案
您需要从操作中返回承诺:
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
.
推荐阅读
- sql-server - T-SQL 处理无结果
- c# - UserDialog 进度条不显示
- php - 重写查询字符串以允许 wordpress 中单个自定义帖子类型的多个 URL
- c++ - 带有 std::quoted 的 Visual Studio 中的错误
- r - RandomForest没有计算OOB错误
- ruby-on-rails - 2 分钟 Rails/AngularJS 后 SSO/SAML 会话超时
- html - 填充整页 div,每边减去填充
- javascript - 为什么javascript不能逐行运行
- react-native - 如何在加载数据时同时渲染 FlatList 的 listItem?
- ruby-on-rails - 多对多 ElasticSearch - Rails