簡體   English   中英

對象可能在帶有 TypeScript 的 Vuex 突變中“未定義”

[英]Object is possibly 'undefined' in Vuex mutation with TypeScript

我正在使用 Vuex 和 TypeScript 學習 Vue.js,在我正在構建的應用程序中,我在 Vuex Store 中遇到了錯誤“對象可能是‘未定義’”。

錯誤發生在這一行的“newCard”突變中:

state.board.lists.find(list => list.id === idList).cards.unshift(card)

完整的商店代碼:

const state: BoardState = {
  board: {
    id: "",
    name: "",
    idProject: "",
    closed: false,
    lists: []
  }
};

const getters: GetterTree<BoardState, {}> = {
  getBoard: state => state.board
};

const mutations: MutationTree<BoardState> = {
  setBoard: (state, board) => (state.board = board),
  newList: (state, list) => state.board.lists.unshift(list),
  newCard: (state, { card, idList }) =>
    state.board.lists.find(list => list.id === idList).cards.unshift(card)
};

const actions: ActionTree<BoardState, {}> = {
  async fetchBoard({ commit }) {
    const response = await axios.post("https://app.fakejson.com/q", json);
    commit("setBoard", response.data);
  },
  async addList({ commit }, list) {
    const response = await axios.post("https://app.fakejson.com/q", {
      token: "oplF0L7vj1Ial4cRqtx9DA",
      data: list
    });
    commit("newList", response.data);
  },
  async addCard({ commit }, { card, idList }) {
    const response = await axios.post("https://app.fakejson.com/q", {
      token: "oplF0L7vj1Ial4cRqtx9DA",
      data: card
    });
    commit("newCard", response.data, idList);
  }
};

打字稿類型:

// Store
export interface BoardState {
  board: Board;
}

// Models
export interface Board {
  id: String;
  name: String;
  idProject: String;
  closed: Boolean;
  lists: List[];
}

export interface List {
  id: String;
  name: String;
  idBoard: String;
  closed: Boolean;
  cards: Card[];
}

export interface Card {
  id: String;
  name: String;
  idList: String;
  closed: Boolean;
}

板子狀態的響應數據是這樣的:

 {
   "id":"1",
   "name":"Tasks",
   "idProject":"1",
   "closed":false,
   "lists":[
      {
         "id":"1",
         "name":"To Do",
         "idBoard":"1",
         "closed":false,
         "cards":[
            {
               "id":"1",
               "idList":"1",
               "name":"Card 1",
               "closed":false
            },
            {
               "id":"2",
               "idList":"1",
               "name":"Card 2",
               "closed":false
            }
         ]
      }
   ]
}

state.board.lists.find(list => list.id === idList).cards.unshift(card)

可能找不到具體列表。 所以你將無法從中挑選卡片。

const list = state.board.lists.find(list => list.id === idList)

if (!list) {
    // do something
    return
}

// list found so return
return list.cards.unshift(card)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM