如何在React-native中循环遍历数组?

时间:2016-10-20 07:00:18

标签: reactjs react-native

使用map函数,但它在console.log上返回无限循环,我无法渲染行返回jsx也尝试了foreach但它没有帮助。无法在jsx中呈现数据。它甚至可以在循环内部控制.log数据。但不是渲染jsx。

import React, { Component } from 'react';
import { TouchableOpacity,DrawerLayoutAndroid,Picker,ListView } from 'react-native';
import { Container, Header, Title, Content,List, ListItem, Text, Button, Icon,InputGroup, Input,View } from 'native-base';
import { Col, Row, Grid } from 'react-native-easy-grid';
import { Actions } from 'react-native-router-flux';
import axios from 'axios';
import styles from '../styles/homestyle';
export default class Home extends Component {

constructor(props) {

super(props);

this.state = {
  user_namez : "",
  user_pazz : "",
};
}
student_data(){

axios.get('http://192.168.0.108/easy_backend/app/app_db/stud_data')

.then((response) => {

  let respdata = response.data ;

  list.respdata(function(y){

    return(<Text>{y.prnt_usernamez}</Text>);

  });

  });

  }

  render() {

   return (

   <View>

    {this.student_data()}

    </View>
    ) 

   } 



   }

1 个答案:

答案 0 :(得分:10)

student_data()不会返回任何内容。所以永远不会从student_data()呈现任何东西。

对于异步调用,您必须使用componentDidMount()

  • 在首页response: [],中添加节点state
  • 将其填入componentDidMount()函数
  • 然后在this.state.response方法
  • 中循环render()

类似的东西:

    export default class Home extends Component {
        constructor(props) {
            super(props);

            this.state = {
                response: [],
                user_namez: "",
                user_pazz: "",
            };
        }

        componentDidMount() {
            axios.get('http://192.168.0.108/easy_backend/app/app_db/stud_data')
            .then((response) => {
                //as soon as the state is updated, component will render using updated values
                this.setState({ response: response});
            });
        }

        render() {
            return (
                <View>
                    {
                        this.state.response.map((y) => {
                            return (<Text>{y.prnt_usernamez}</Text>);
                        })
                    }
                </View>
            );
        }
    }