簡體   English   中英

反應 typescript state Object 可能是“未定義”錯誤

[英]react typescript state Object is possibly 'undefined' error

我是使用 typescript 的新手。 我有一個應用程序,我調用 api 並將響應設置為 state。 我為 api 調用創建了一個通用類型,如下所示。

const responseBody = <T>(response: AxiosResponse<T>) => response.data;
const restApiCalls = {
  get: <T>(url: string) => axios.get<T>(url).then(responseBody),
  post: <T>(url: string, body: {}) =>
    axios.post<T>(url, body).then(responseBody),
  put: <T>(url: string, body: {}) => axios.put<T>(url, body).then(responseBody),
};

const users = {
  getUsers: () =>
    restApiCalls.get<Users[]>("https://jsonplaceholder.typicode.com/users"),
};

const apis = {
  users,
};
export default apis;

getUser() function 調用get請求並返回Users列表

以下是User interface

export interface Users {
  id: boolean;
  name: string;
  username: string;
  email: string;
  address: Address;
  phone: string;
  website: string;
  company: Company;
}

interface Address {
  street: string;
  suite: string;
  city: string;
  zipcode: string;
  geo: Geo;
}

interface Geo {
  lat: string;
  lng: string;
}

interface Company {
  name: string;
  catchPhrase: string;
  bs: string;
}

調用api時,api返回數據成功,我使用setUser方法將返回的數據賦值給state。

以下是 state。

const [user, setUser] = useState<Users[]>();

我將獲取的數據分配給 state,如下所示。

useEffect(() => {
    const fetchData = async () => {
      const res = await apis.users.getUsers();
      
      setUser(res);
    };
    fetchData();
  }, []);

當控制台user state 時,數據在那里並且記錄成功。 但我想在 if 條件下檢查用戶 state 的長度。 如果我檢查長度,它會顯示以下錯誤。

Object is possibly 'undefined'.ts(2532)

這是我用來檢查長度的代碼

 const someFunction= () => {
    if (user?.length > 1) {
      for (let index = 0; index < user?.length; index++) {
        console.log(user[index])
      }
    }
  };

但是我如果將 state 類型設置為any而不是User[] ,它可以工作。 可能是什么問題?

帶有users的表達式都能夠解析為undefined ,它不能與數字進行比較,也不能被索引。 例如user?.length可能未定義(如果user未定義); user[index]相同

您需要處理未定義的情況。 例如:

 const someFunction= () => {
    if(!user) { return; }
    if (user.length > 1) {
      for (let index = 0; index < user.length; index++) {
        console.log(user[index])
      }
    }
  };

暫無
暫無

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

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