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

IT技术 reactjs react-native
2021-04-29 08:33:44

使用了 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个回答

student_data()不返回任何东西。所以什么都不会从student_data().

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

  • response: [],在 Home 中添加一个节点state
  • 填入一个componentDidMount()函数
  • 然后this.state.responserender()方法中循环

就像是:

    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>
            );
        }
    }