英文:
React Native referenced object seems to be undefined
问题
我正试图将从API检索到的数据分配到一个数组中,但是每当调用数据时,我的项目就会崩溃,我会收到一个错误,错误信息是TypeError: undefined is not an object (evaluating 'this.data.name')
以下是关于变量data
的所有代码:
constructor(props){
super(props);
this.state={
data : [],
}
}
async componentDidMount(){
try {
const id = this.props.navigation.state.params.info
const res = await axios.request({
method: 'get',
url: `https://developers.zomato.com/api/v2.1/restaurant?res_id=${id}`,
headers: {
'Content-Type': 'application/json',
'user-key': 'a31bd76da32396a27b6906bf0ca707a2'
}
});
this.setState({ data: res.data });
} catch (err) {
console.log(err);
} finally {
this.setState({ isLoading: false });
}
};
render() {
return (
<View>
{this.state.isLoading ?
<View style={{ flex: 1, marginTop: 200 }}>
<ActivityIndicator style={{color:'red'}} />
</View> :
<View><Text>{this.state.data.name}</Text></View>
}
</View>
)}
英文:
I am trying to assign data retrieved from an API into an array, however whenever the data is called my project crashed and I get an error saying TypeError: undefined is not an object (evaluating 'this.data.name')
Here is all my code regarding the variable data
constructor(props){
super(props);
this.state={
data : [],
}
}
async componentDidMount(){
try {
const id = this.props.navigation.state.params.info
const res = await axios.request({
method: 'get',
url: `https://developers.zomato.com/api/v2.1/restaurant?res_id=${id}`,
headers: {
'Content-Type': 'application/json',
'user-key': 'a31bd76da32396a27b6906bf0ca707a2'
}
});
this.setState({ data: res.data });
} catch (err) {
console.log(err);
} finally {
this.setState({ isLoading: false });
}
};
render() {
return (
<View>
{this.state.isLoading ?
<View style={{ flex: 1, marginTop: 200 }}>
<ActivityIndicator style={{color:'red'}} />
</View> :
<View><Text>{this.data.name}</Text></View>
}
</View>
)}
答案1
得分: 1
基本上问题在于你在状态中存储了数值,但在引用该数值时没有提供状态,所以只需这样做,
<View><Text>{this.state.data.name}</Text></View>
希望能有所帮助。有疑问请随时提问。
英文:
Basically the problem is you are storing in the state, but while referring the value you are not providing state, so just do ,
<View><Text>{this.state.data.name}</Text></View>
Hope it helps. Feel free for doubts.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论