如何在React Native中显示来自API的数据,而不会出现未定义的错误属性



在显示时使用dataSource[0].first_name时,总是会出现未定义的属性错误。

export default class Profile extends React.Component {
constructor(props) {
super(props)
this.state = {
dataSource: []
}
}
async componentDidMount() {
const response = await fetch('http://api url goes here /api/v1/getUserInfo/40', {
method: 'GET',
headers: {
'authorization': 'token ' + global.storeToken,
}
})
.then((response) => {
return response;
})
.catch((error) => {
alert('Error!' + error)
})
const json = await response.json();
this.setState({
isLoading: false,
dataSource: [json],
});
}
render() {
const { dataSource } = this.state;
return (
<Container>
<Header span style={styles.headerStyle}>
<Body style={{ justifyContent: "center" }}>
<Label style={styles.labelNickname}></Label>
<Label style={styles.labelUserID}> {dataSource[0].first_name}</Label>
</Body>
</Header>
</Container>
);
};
}

api内容为:

{
"id": 40,
"email": "kk@gmail.com",
"first_name": "Kagura",
"last_name": "Kinomoto",
"birth_date": "1990-01-01T00:00:00.000Z"
}

总是有错误的。

TypeError: Cannot read property 'first_name' of undefined
This error is located at:
in Profile (at SceneView.js:9)
in SceneView (at StackViewLayout.tsx:898)
in RCTView (at View.js:35)
in View (at StackViewLayout.tsx:897)
etc...

奇怪的是,在所有控制台日志和其他东西之后,它昨天工作了。我只是休眠了笔记本电脑,当我今天再次尝试运行它时,错误又回来了。

将此行更新为以下内容。

{dataSource && dataSource[0] && dataSource[0].first_name}

这将确保dataSource[0]不是undefined

原因是您的fetch请求是异步的,因此在收到响应之前dataSource[0]是未定义的。

最新更新