我有一个承诺,当我为特定用户获取数据时,我将使用它来设置状态。以下是该代码:
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
都没问题。。谢谢!
答案 0 :(得分:2)
您必须先检查username
的类型,然后才能使用它,因为该函数将返回两个具有不同属性的值(void和AxiosResponse)
所以您必须像这样检查:
.then(username => {
// Check if it is not void
if (this.hasBeenMounted && username ) {
this.setState({
user: username.data
});
}
})