我正在尝试将React-native程序与SQL Server中的某些数据连接起来。这是我们的链接返回的Json字符串:
[{"Item_ID":2,"first_name":"steve","last_name":"jones","phone":"510-712-1822","email":"sjones@waltersandwolf.com","company":"Glass"},{"Item_ID":4,"first_name":"Tina","last_name":"Wills","phone":"510-222-7788","email":"twills@waltersandwolf.com","company":"Glass","notes":"","json":"{fname: \"Tina\", lname: \"Wills\", phone: \"510-222-7788\", email: \"twills@waltersandwolf.com\", company: \"Glass\", project: \"Portal\"}"},{"Item_ID":5,"first_name":"Sleepy","last_name":"owl","phone":"555-555-5555","email":"owl@forest.com","company":"Forest","notes":"whoooooo","json":"{first_name:sleepy,last_name:owl, phone:55555555,company:Forest, email: owl, notes:whoooo}"}]
使用我在网上找到的代码段,我试图将其显示在平面视图中,但是它是空白的:
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, FlatList, Text, View, Alert, ActivityIndicator, Platform} from 'react-native';
export default class App extends Component {
constructor(props)
{
super(props);
this.state = {
isLoading: true
}
}
componentDidMount() {
return fetch('https://functions-ww.azurewebsites.net/api/SteveListJSON')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson
}, function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
});
}
FlatListItemSeparator = () => {
return (
<View
style={{
height: 1,
width: "100%",
backgroundColor: "#607D8B",
}}
/>
);
}
GetFlatListItem (company) {
Alert.alert(company);
}
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.MainContainer}>
<FlatList
data={ this.state.dataSource }
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem={({item}) => <Text style={styles.FlatListItemStyle} onPress={this.GetFlatListItem.bind(this, item.company)} > {item.company} </Text>}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer :{
justifyContent: 'center',
flex:1,
margin: 10,
paddingTop: (Platform.OS === 'ios') ? 20 : 0,
},
FlatListItemStyle: {
padding: 10,
fontSize: 18,
height: 44,
},
});
感谢您能提供的任何帮助。我是新手,所以可能是我想念的简单事情...
答案 0 :(得分:0)
URL以字符串形式返回响应,并且您需要的数据源是一个对象,因此在设置数据源的状态之前,请将其更改为一个对象。 添加此:-
this.setState({
isLoading: false,
dataSource: JSON.parse(responseJson)
}