【发布时间】:2020-04-20 03:48:36
【问题描述】:
我正在调用发出 JSON 的 API 我正在 componentDidMount 和 setState 中调用这个 promise api 函数,然后在 render 方法中调用它,但它总是发出 null 错误。
请帮帮我
位置界面
export interface ILocation {
info: Info;
options: Options;
results: Result[];
}
interface Result {
providedLocation: ProvidedLocation;
locations: Location[];
}
interface Location {
street: string;
adminArea6: string;
adminArea6Type: string;
adminArea5: string;
adminArea5Type: string;
adminArea4: string;
adminArea4Type: string;
adminArea3: string;
adminArea3Type: string;
adminArea1: string;
adminArea1Type: string;
postalCode: string;
geocodeQualityCode: string;
geocodeQuality: string;
dragPoint: boolean;
sideOfStreet: string;
linkId: string;
unknownInput: string;
type: string;
latLng: LatLng;
displayLatLng: LatLng;
mapUrl: string;
}
interface ProvidedLocation {
latLng: LatLng;
}
interface LatLng {
lat: number;
lng: number;
}
interface Options {
maxResults: number;
thumbMaps: boolean;
ignoreLatLngInput: boolean;
}
interface Info {
statuscode: number;
copyright: Copyright;
messages: any[];
}
interface Copyright {
text: string;
imageUrl: string;
imageAltText: string;
}
IWeatherStates
export interface IWeatherStates {
Locations: ILocation
}
获取位置
private getLocation(latitudes: number, longitude: number): Promise<ILocation> {
let promise: Promise<ILocation> = new Promise<ILocation>((resolve, reject) => {
let query = `${this.LIST_API_ENDPOINT}/location/${latitudes},${longitude}`
this.props.httpClient.get(query, HttpClient.configurations.v1, this.httpClientOptions).then((rawResponse: HttpClientResponse) => {
return rawResponse.json()
}).then((jsonResponse) => {
resolve(jsonResponse)
})
})
return promise
}
}
componentDidMount
public componentDidMount() {
this.getLocation(29.378586, 47.990341).then((location: ILocation) => {
this.setState({
Locations: location
})
})
}
建筑
constructor(props: IWeatherProps) {
super(props)
this.state = {
Locations: null
}
}
**给出错误的渲染**
public render(): React.ReactElement<IWeatherProps> {
return (
<div className={styles.weather}>
{this.state.Locations.results[0].locations[0].adminArea5}
</div>
)
}
{this.state.Locations.results[0].locations[0].adminArea5} 结果给出空错误
【问题讨论】:
-
您希望如何从 null 获取索引 0?
-
添加检查位置是否为空,呈现“未加载位置”等
-
在 componentDidMount 如果我把 console.log 它给出输出
-
把console放到render函数里你会看到null
-
是的,为什么会这样!!
标签: javascript json reactjs typescript