如何通过发布请求API在ListView上显示JSON数据React Native

时间:2019-02-19 10:44:25

标签: javascript ajax reactjs react-native

在这里,我试图从API post方法中获取数据并尝试在listview上进行填充,在选择了特定数据之后,我将转到网页。 通过get方法,我已经做到了。 但是,当我运行此代码时,空白列表就要来了。 如何解析groupData.name中的值?在列表中获取数据后,我可以选择特定数据并发送到其他屏幕,但是现在,我如何填充列表中的数据?

    import React, { Component } from 'react';
    import { View, Text, TextInput,   
    FooterTab,Button,TouchableOpacity, ScrollView,ListView, StyleSheet,
     ActivityIndicator ,Header,icon} from 'react-native';

    import { createStackNavigator } from 'react-navigation';  
    import { SearchBar } from 'react-native-elements';


    const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });

   class RenderList extends Component {
  static navigationOptions = {
    title: 'Selected Item',
    header: null,
  };
  constructor() {
    super();
    this.state = {
      data: null,
      loading: true,
      search: '',
    };
  }

  componentDidMount() {
    this.createViewGroup();
  }

  createViewGroup = async () => {
    try {
      const response = await fetch(
        'http:///Dsenze/userapi/grouphier/viewgroup',
        {
          method: 'POST',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            password: 'admin',
            username: 'admin',
            viewall: 'false',
            id: [4],
            startlimit: '0',
            valuelimit: '10',
          }),
        }
      );

      const responseJson = await response.json();

      const { groupData } = responseJson;

      this.setState({
        data: groupData,
        loading: false,
      });
    } catch (e) {
      console.error(e);
    }
  };

  clickedItemText(clickedItem) {
    this.props.navigation.navigate('Item', { item: clickedItem });
  }
  updateSearch = search => {
    this.setState({ search });
  };
  keyExtractor = ({ id }) => id.toString();
  renderItem = ({ item }) => (
    <TouchableOpacity
      style={styles.item}
      activeOpacity={0.4}
      onPress={() => {
        this.clickedItemText(item);
      }}>
      <Text style={styles.text}>Hospital name {name}</Text>
    </TouchableOpacity>
  );
  render() {
    const { loading, data } = this.state;
    return (
      <ScrollView>
        <View style={styles.container1}>
          {this.state.loading ? (
            <ActivityIndicator size="large" />
          ) : (
            <FlatList
              data={data}
              renderItem={this.renderItem}
              keyExtractor={this.keyExtractor}
            />
          )}
        </View>
      </ScrollView>
    );
  }
}   
    class ClickedItem extends Component
    {

        constructor() {
            super();
            this.state = {
              inputValue: '',
              // Default Value of the TextInput
              // Default value for the QR Code
            };
          }

        static navigationOptions = 
        {
            title: "Selected Item",
            header:  null
        };

        render()
        {

            return(
                <ScrollView>
                <View style = { styles.container2 }>

        <TextInput style={styles.inputBox}
         underlineColorAndroid='rgba(0,0,0,0)'
          placeholder="Hospital Id"
          editable={false}
          placeholderTextColor="#000000"
          onChangeText={(hospital_id) => this.setState({hospital_id})}>{ this.props.navigation.state.params.item.id }</TextInput>

       <TextInput   style={styles.inputBox}
         underlineColorAndroid='rgba(0,0,0,0)'
          placeholder="Field 2"
          secureTextEntry={false}
          placeholderTextColor="#000000"
          onChangeText={(Field2) => this.setState({Field2})}/>

    <TouchableOpacity style={styles.button}onPress={() => {Insert(this.state.hospital_id,this.state.Field2,this.state.Field3,this.state.Field4,this.state.Field5,this.state.Field6);{this.getTextInputValue}}}>
              <Text style={styles.buttonText}>Insert</Text>
          </TouchableOpacity>
                </View>
                </ScrollView>
            );
        }
    }
    export default InvDemoPost = createStackNavigator(
    {
        List: { screen: RenderList,
                 header: true},

        Item: { screen: ClickedItem,
                header: null }
    });


    const styles = StyleSheet.create(
    {
        container1:
        {
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center'
        },

        container2:
        {
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
            paddingHorizontal: 15
        },

        inputBox:{
            width:300,
            borderColor: '#48BBEC',
            backgroundColor: '#F8F8FF',
            borderRadius:25,
            paddingHorizontal:16,
            fontSize:16,
            color:'#000000',
            marginVertical:10, 

        },
        button:{
            width:300,
            backgroundColor:'#4169E1',
            borderRadius:25,
            marginVertical:10,
            paddingVertical:16
        },

        buttonText:{
        fontSize:16,
        fontWeight:'500',
        color:'#ffffff',
        textAlign:'center'

        },

        item:
        {
            padding: 15
        },

        text:
        {
            fontSize: 18
        },

        separator:
        {
            height: 2,
            backgroundColor: 'rgba(0,0,0,0.5)'
        }
    });

下面是Json数据,我必须在列表视图中填充

{
      "groupData": [{
        "hierarchy": 4,
        "id": 4,
        "name": "St.Mary's Hospitals",
        "parent": 3,
        "type": 2
      }, {
        "hierarchy": 4,
        "id": 5,
        "name": "Mandya Clinic",
        "parent": 6,
        "type": 2
      }, {
        "hierarchy": 4,
        "id": 7,
        "name": "Blr Clinic",
        "parent": 3,
        "type": 2
      }, {
        "hierarchy": 4,
        "id": 8,
        "name": "kings hospital",
        "parent": 3,
        "type": 2
      }, {
        "hierarchy": 4,
        "id": 9,
        "name": "jason hospital",
        "parent": 3,
        "type": 1
      }],
      "success": "true"
    }

1 个答案:

答案 0 :(得分:1)

我正在使用以下输出:

{
      "groupData": [{
        "hierarchy": 4,
        "id": 4,
        "name": "St.Mary's Hospitals",
        "parent": 3,
        "type": 2
      }, {
        "hierarchy": 4,
        "id": 5,
        "name": "Mandya Clinic",
        "parent": 6,
        "type": 2
      }, {
        "hierarchy": 4,
        "id": 7,
        "name": "Blr Clinic",
        "parent": 3,
        "type": 2
      }, {
        "hierarchy": 4,
        "id": 8,
        "name": "kings hospital",
        "parent": 3,
        "type": 2
      }, {
        "hierarchy": 4,
        "id": 9,
        "name": "jason hospital",
        "parent": 3,
        "type": 1
      }],
      "success": "true"
    }

假设此对象已分配给this.state.dataSource

<FlatList
  data={this.state.dataSource.groupData}
  renderItem={({item: { name }) => <Text>{name}</Text>}
  keyExtractor={({id}) => id.toString()}
/>

但是,您必须记住,您正在componentDidMount中获取数据,该数据在第一个render之后被调用。这意味着this.state.dataSource将为空,直到您的API调用成功为止。

您可以添加其他状态变量isLoading。然后在render函数中,您可以根据API调用的状态,有一些逻辑来呈现Spinner或List。

render() {
  const { isLoading, dataSource: { groupData } } = this.state;
  if(isLoading) {
    return <Text>Loading</Text>
  }
  return (
    <FlatList
      data={groupData}
      renderItem={({item: { name }) => <Text>{name}</Text>}
      keyExtractor={({id}) => id.toString()}
    />
  )
}

然后在API调用的逻辑中,在其中设置dataSource,然后可以将isLoading设置为false

已更新以反映相关代码

class RenderList extends Component {
  static navigationOptions = {
    title: 'Selected Item',
    header: null,
  };
  constructor() {
    super();
    this.state = {
      data: null,
      loading: true,
      search: '',
    };
  }

  componentDidMount() {
    this.createViewGroup();
  }

  createViewGroup = async () => {
    try {
      const response = await fetch(
        'http:///Dsenze/userapi/grouphier/viewgroup',
        {
          method: 'POST',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            password: 'admin',
            username: 'admin',
            viewall: 'false',
            id: [4],
            startlimit: '0',
            valuelimit: '10',
          }),
        }
      );

      const responseJson = await response.json();

      const { groupData } = responseJson;

      this.setState({
        data: groupData,
        loading: false,
      });
    } catch (e) {
      console.error(e);
    }
  };

  clickedItemText(clickedItem) {
    this.props.navigation.navigate('Item', { item: clickedItem });
  }
  updateSearch = search => {
    this.setState({ search });
  };
  keyExtractor = ({ id }) => id.toString();
  renderItem = ({ item }) => (
    <TouchableOpacity
      style={styles.item}
      activeOpacity={0.4}
      onPress={() => {
        this.clickedItemText(item);
      }}>
      <Text style={styles.text}>Hospital name {name}</Text>
    </TouchableOpacity>
  );
  render() {
    const { loading, data } = this.state;
    return (
      <ScrollView>
        <View style={styles.container1}>
          {this.state.loading ? (
            <ActivityIndicator size="large" />
          ) : (
            <FlatList
              data={data}
              renderItem={this.renderItem}
              keyExtractor={this.keyExtractor}
            />
          )}
        </View>
      </ScrollView>
    );
  }
}