以下代碼給我這個錯誤:「無法讀取未定義的屬性'CityName'」。但是當我調試代碼時,數據狀態僅在第一次渲染時爲空,並且在那之後數據已經從API接收到數據。有沒有辦法強制渲染忽略第一個空狀態?狀態在第一次渲染時爲空
class profile extends Component {
constructor(props) {
super(props);
this.state = {
data :[],
};
}
componentWillMount() {
axios.get(BASE_URL + 'user/' + 1)
.then(response => this.setState({data: response.data.Result}))
.catch(error => console.log(error));
}
render() {
return (
<View>
<Text>{this.state.data.Profile.CityName}</Text>
</View>
);
}
}
非常好,它的工作。但我仍然不明白是什麼在做const {data = undefined} = this.state。 – Nima
這是ES6的「解構」功能。本質上它和'const data = this.state.data'是一樣的,所以只是將一個對象的字段明確分配給一個變量的較短版本。 – cubbuk