[英]Property `data` does not exist on Type <void> | AxiosHttpResponse<any>
我有一个承诺,当我为特定用户获取数据时,我使用它来设置状态。 下面是代码:
getUserUsername = (): string => {
const { match } = this.props;
return match.params.username;
};
onFetchUser = () =>
getUser(this.getUserUsername())
.then(username => {
if (this.hasBeenMounted) {
this.setState({
user: username.data // The error is here.
});
}
})
.catch((errorResponse: HttpResponseObj | null = null) => {
if (this.hasBeenMounted) {
this.setState({
isLoading: false,
user: null,
errorMessage: errorResponse
});
}
});
但我收到这个 TS 错误说:
Property 'data' does not exist on type 'void | AxiosResponse<IUser>'.
Property 'data' does not exist on type 'void'.ts(2339)
---
any
getUser()
是我使用的服务,它的代码在这里:
export const getUser = (username: string, initialOptions = {}): HttpResponse<IUser> => {
const options = {
method: httpMethod.GET,
url: endpoint.GET_USER(username)
};
return Instance(options, lensesOptions);
};
HttpResponse 的代码在这里:
export interface HttpResponse<T> extends Promise<void | AxiosResponse<T>> {}
我试过类似的东西:
.then((username): HttpResponse<any> => { // Doesn't work though
if (this.hasBeenMounted) {
this.setState({
user: username.data
});
}
})
这是 Axios 接口:
export interface AxiosResponse<T = any> {
data: T;
status: number;
statusText: string;
headers: any;
config: AxiosRequestConfig;
request?: any;
}
你能向我解释一下是什么问题。 我去 axios 接口,我看到它的data
,以及generic
没有问题..谢谢!
您必须在尝试使用之前检查username
的类型,因为该函数返回具有不同属性的两个值(void 和 AxiosResponse)
所以你必须像这样检查:
.then(username => {
// Check if it is not void
if (this.hasBeenMounted && username ) {
this.setState({
user: username.data
});
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.