反应打字稿状态对象可能是 'undefined' 错误

react typescript state Object is possibly 'undefined' error

我刚开始使用带有 React 的打字稿。我有一个应用程序,我在其中调用 api 并将响应设置为状态。我已经为 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()函数调用get请求和returns列表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 returns数据成功,我使用setUser方法将返回的数据分配给状态。

状态如下

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

我将获取的数据分配给如下状态。

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

当控制 user 状态时,数据就在那里并且记录成功。但是我想在 if 条件下检查用户状态的长度。如果我检查长度,它会显示以下错误。

Object is possibly 'undefined'.ts(2532)

这是我用来检查长度的代码

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

但我如果将状态类型设置为 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])
      }
    }
  };