[英]Render async fetch response as an element in React-Native?
I have an array of data I'm getting back from an API using fetch. 我有一系列要使用API从API取回的数据。 I'm trying to parse and render the json response as elements in my app, however I'm not having any luck, how would I go about fixing my code to render my async data as elements?
我正在尝试将json响应解析并呈现为我的应用程序中的元素,但是我没有任何运气,我该如何修复将代码呈现为元素的异步代码?
class Profile extends React.PureComponent {
static propTypes = {
navigation: PropTypes.object,
handleLogout: PropTypes.func,
user: PropTypes.object,
};
static navigationOptions = {
headerVisible: true,
title: 'Profile',
};
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount() {
fetch("http://10.0.2.2:8080/combined",
{ method: 'get' })
.then(function(response) {
var data = response.json();
console.log(data)
this.setState({ data })
})
.catch(function(err) { }
);
};
logout = () => {
const callback = () => {
const resetAction = NavigationActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'SignIn' })],
});
this.props.navigation.dispatch(resetAction);
};
this.props.handleLogout(callback);
};
jsonData() {
return this.state.data.map(function(rows, i){
return(
<View key={i}>
<Text>{rows.FIRSTNAME}</Text>
</View>
);
});
}
render() {
const { user } = this.props;
let email;
return (
<ContentWrapper>
<View style={styles.container}>
<Image style={styles.header} source={images.profileHeader} />
<View style={styles.body}>
<Avatar email={email} style={styles.avatar} />
<Text style={styles.email}>{_.capitalize(email)}</Text>
{jsonData()}
<Button
title="Log out"
icon={{ name: 'logout-variant', type: 'material-community' }}
onPress={this.logout}
style={styles.logoutButton}
/>
</View>
</View>
</ContentWrapper>
);
}
}
export default Profile;
Remember, response.json()
is asynchronous as well and returns Promise
, not data as you expect. 请记住,
response.json()
也是异步的,并且返回Promise
,而不是您期望的数据。
Adjust code responsible for fetching to this and you are good to go... 调整负责获取此代码的代码,您就可以开始了。
componentDidMount() {
fetch("http://10.0.2.2:8080/combined", { method: 'get' })
.then(response => response.json())
.then(data => {
this.setState({ data })
})
.catch(function(err) {
//
})
}
You can set it so it only renders if data has a length: 您可以设置它,使其仅在数据具有长度时才呈现:
jsonData = () => (this.state.data.length ? this.state.data.map((rows, i) => (
<View key={i}>
<Text>{rows.FIRSTNAME}</Text>
</View>
)) : null)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.