javascript - 有没有一种方法可以在 TypeScript 中处理对象类型的对象?
我使用过 React 和 TypeScript,并从 API 获取数据。获取数据后,它会被保存为 coin 对象。在等待状态下,它可能没有数据。因此,coin 可能为 null。如果 coin 为 null,那么我们就无法获取该对象的 image 字段。以前有人处理过这个问题吗?请给我一些建议。我没有 TypeScript 的经验。下面是我的代码:
import React, { Component } from 'react'
import axios from 'axios';
import CoinIcon from './CoinIcon';
interface CoinDetailProps{
id:string;
}
interface CoinImage {
thumb: string ;
small: string ;
large: string ;
}
interface Coin {
id: string,
symbol: string,
name: string,
image: CoinImage | null,
description: string
}
interface CoinState{
coin : Coin;
loaded: boolean;
}
export class CoinDetail extends Component<CoinDetailProps,CoinState> {
constructor(props) {
super(props)
const init = {} as Coin;
this.state = {
coin : init,
loaded: false,
}
}
loadData = () => {
const {id} = this.props;
const url = `https://api.coingecko.com/api/v3/coins/${id}`;
axios.get(url)
.then(response => {
const data = response.data
this.setState({
coin: data,
loaded: true
})
})
.catch((error) => {console.log("Something went wrong. ", error)})
}
componentDidMount() {
this.loadData();
}
componentDidUpdate(prevProps, prevState) {
if (prevProps !== this.props) {
this.loadData();
}
}
render()
{
const {loaded, coin} = this.state;
console.log("coin image:" + coin.image.small)
return (
<div>
<CoinIcon name={coin.name} symbol = {coin.symbol} image={coin.image.small} />
</div>
)
}
}
export default CoinDetail
当我尝试打印出像这样的内容时:
console.log(coin.image.small) <=== error here: Object is possibly 'null'.
答案#1
你可以明确地检查:
if (coin.image) {
console.log(coin.image.small);
} else {
// Do something else
}
或者你可以使用可选链:
console.log(coin.image?.small);
