将异步获取响应渲染为React-Native中的元素?

时间:2017-05-16 19:03:49

标签: javascript reactjs asynchronous react-native

我有一个数据数组,我正在使用fetch从API中获取。我正在尝试解析并将json响应呈现为我的应用程序中的元素,但是我没有运气,我将如何修复我的代码以将异步数据呈现为元素?

Here's the data I'm trying to render

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;

2 个答案:

答案 0 :(得分:3)

请记住,response.json()也是异步的,并返回Promise,而不是您期望的数据。

调整负责获取此代码的代码,你很高兴...

componentDidMount() {
  fetch("http://10.0.2.2:8080/combined", { method: 'get' })
    .then(response => response.json())
    .then(data => {
      this.setState({ data })
    })
   .catch(function(err) {
     // 
   })
}

答案 1 :(得分:0)

您可以对其进行设置,使其仅在数据具有长度时呈现:

jsonData = () => (this.state.data.length ? this.state.data.map((rows, i) => (
  <View key={i}>
    <Text>{rows.FIRSTNAME}</Text>
  </View>
)) : null)