【发布时间】:2019-08-16 22:45:17
【问题描述】:
我有一个承诺,当我为特定用户获取数据时,我使用它来设置状态。下面是代码:
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没问题。。谢谢!!
【问题讨论】:
标签: javascript reactjs typescript axios