programing

그러면 Vuex에서 getter가 있는 스토어 상태를 약속과 함께 가져올 수 없음

prostudy 2022. 5. 22. 11:24
반응형

그러면 Vuex에서 getter가 있는 스토어 상태를 약속과 함께 가져올 수 없음

그들이 입력하는 채널 루트에 PIN 코드가 필요한지 여부를 확인하고 싶기 때문에, 나는 라우터를 사용한다.각각 아래와 같이:

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.

참조URL: https://stackoverflow.com/questions/65855176/cannot-get-store-states-with-getters-in-vuex-with-promise-then

반응형