如何在ListView上显示json数据通过post request api做出反应 [英] How to display json data on ListView react native by post request api
问题描述
这里我试图从API post方法中获取数据并尝试在listview上填充,在选择特定数据后,我将转到网页。
通过get方法我已经完成了。
但是当我运行此代码时,空白列表即将到来。
如何解析groupData.name中的值?获取列表中的数据后,我可以选择特定数据并发送到其他屏幕,但是现在,我如何在列表中填充数据?
从'react'导入React,{Component};
从'react-native'导入{View,Text,TextInput,
FooterTab,Button,TouchableOpacity,ScrollView,ListView,StyleSheet,
ActivityIndicator,Header,icon};
从'react-navigation'导入{createStackNavigator};来自'react-native-elements'的
import {SearchBar};
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' ,
标题:{
接受:'application / json',
'Content-Type':'application / json',
},
body:JSON。 stringify({
密码:'admin',
用户名:'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}>医院名称{name}< / Text>
< / TouchableOpacity>
) ;
render(){
const {loading,data} = this.state;
return(
< ScrollView>
< View style = {styles.container1}>
{this.state.loading?(
< ActivityIndicator size =大/>
):(
< FlatList
data = {data}
renderItem = {this.renderItem}
keyExtractor = {this。 keyExtractor}
/>
)}
< / View>
< / ScrollView>
);
}
}
class ClickedItem extends Component
{
constructor(){
super();
this.state = {
inputValue:'',
// TextInput的默认值
// QR码的默认值
};
}
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)'
占位符=字段2
secureTextEntry = {false}
placeholderTextColor =#000000
onChangeText = {(Field2)=> this.setState({Field2})} />
< TouchableOpacity style = {styles.button} onPress = {()=> {Insert(this.state.hospital_id,this.state.Field2,this.stat e.Field3,this.state.Field4,this.state.Field5,this.state.Field6); {this.getTextInputValue}}}>
< Text style = {styles.buttonText}> Insert< / Text>
< / TouchableOpacity>
< /查看>
< / ScrollView>
);
}
}
导出默认值InvDemoPost = createStackNavigator(
{
List:{screen:RenderList,
header:true},
项目:{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,
},
按钮:{
宽度:300,
backgroundColor:'#4169E1',
borderRadius: 25,
marginVertical:10,
paddingVe rtical: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
},{
层次结构:4,
id:7,
name:Blr Clinic,
parent:3,
type: 2
},{
层次结构:4,
id:8,
名称:国王医院,
父母:3 ,
type:2
},{
hierarchy:4,
id:9,
name:jason hospital,
parent:3,
type:1
}],
成功:true
}
我使用以下输出:
{
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,
名称:国王医院,
父母:3,
类型:2
},{
hierarchy:4,
id:9,
name:jason hospital,
parent:3,
type:1
}],
成功:真实
}
假设这个对象分配给 this.state.dataSource
< FlatList
data = {this.state.dataSource.groupData}
renderItem = {({item:{name})=> <文字> {name}< / Text>}
keyExtractor = {({id})=> id.toString()}
/>
但是,你必须记住你在 componentDidMount中获取数据
,在第一个 render
之后调用。这意味着 this.state.dataSource
将为空,直到您的API调用成功为止。
您可以添加一个额外的状态变量 isLoading
。然后在你的渲染
函数中你可以有一些逻辑来渲染一个微调器或一个列表,具体取决于你的API调用的状态。
render(){
const {isLoading,dataSource:{groupData}} = this.state;
if(isLoading){
return< Text> Loading< / Text>
}
返回(
< 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' ,
标题:{
接受:'application / json',
'Content-Type':'application / json',
},
body:JSON。 stringify({
密码:'admin',
用户名:'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}>医院名称{name}< / Text>
< / TouchableOpacity>
) ;
render(){
const {loading,data} = this.state;
return(
< ScrollView>
< View style = {styles.container1}>
{this.state.loading?(
< ActivityIndicator size =大/>
):(
< FlatList
data = {data}
renderItem = {this.renderItem}
keyExtractor = {this。 keyExtractor}
/>
)}
< / View>
< / ScrollView>
);
}
}
Here I am trying to fetch data from API post method and trying to populate on listview , and after selecting particular data I'll go to net page. By get method I have done that. But when I am running this code blank list is coming . How can I parse value from groupData.name? After getting data on list I can select particular data and send to other screen ,but for now , how can I populate data in list?
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)'
}
});
Below is the Json data ,that I have to populate on the list view
{
"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"
}
I am using the following output:
{
"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"
}
Assuming this object is assigned to this.state.dataSource
<FlatList
data={this.state.dataSource.groupData}
renderItem={({item: { name }) => <Text>{name}</Text>}
keyExtractor={({id}) => id.toString()}
/>
But, you must remember that you're fetching data in componentDidMount
, which is called after the first render
. This means that this.state.dataSource
will be empty until your API call has succeeded.
You could add an additional state variable isLoading
. Then inside your render
function you could have some logic to render a Spinner or a List, depending on the status of your API call.
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()}
/>
)
}
Then inside of the logic of your API call, where you set dataSource
, you can then set isLoading
to false
.
Updated to reflect code in question
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>
);
}
}
这篇关于如何在ListView上显示json数据通过post request api做出反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!