这可能是一个愚蠢的问题我试图从服务器获取json数组并在listview中设置它,今天只有我开始做反应js这么混淆如何做到这一点,得到null不是一个对象(评估'this.state。数据源')不知道在哪里犯错误让我发布我的代码到目前为止我尝试了这是index.android代码:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
ListView,
View
} from 'react-native';
export default class SecondProject extends Component {
constructor(props) {
super(props);
this.dataSource = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
})
}
componentDidMount () {
this.getContractList()
}
render() {
this.setState({ dataSource: this.state.dataSource.cloneWithRows(responseJson)});
return (
<View style={{flex: 1, paddingTop: 22}}>
<ListView
dataSource={rows}
renderRow={(rowData) => <Text>{rowData}</Text>}
/>
</View>
);
}
getContractList() {
return fetch('url')
.then((response) => response.json())
.then((responseJson) => {
this.setState({isLoading: false, jsonData: responseJson});
/// console.log(responseJson);
return responseJson;
})
.catch((error) => {
// console.error(error);
});
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('SecondProject', () => SecondProject);
这是来自服务器的json响应:
[
{
"HeaderText":"Contract Approval",
"ApprovalType":"C",
"ApprovalCount":0,
"SubText":"New / Change",
"ApproverID":198
},
{
"HeaderText":"Contract Specification Approval",
"ApprovalType":"CS",
"ApprovalCount":0,
"SubText":"New / Change",
"ApproverID":198
},
{
"HeaderText":"Spare Part Request Approval",
"ApprovalType":"SPR",
"ApprovalCount":0,
"SubText":"New / Change",
"ApproverID":198
},
{
"HeaderText":"Spare Part Non Return Approval",
"ApprovalType":"SPNR",
"ApprovalCount":0,
"SubText":"New / Change",
"ApproverID":198
},
{
"HeaderText":"Spare Purchase Request Approval",
"ApprovalType":"SPRA",
"ApprovalCount":0,
"SubText":"New / Change",
"ApproverID":198
},
{
"HeaderText":"Spare Request Approval",
"ApprovalType":"SSRA",
"ApprovalCount":0,
"SubText":"New / Change",
"ApproverID":198
}
]
如何处理这个问题,有人可以提前感谢!!
答案 0 :(得分:3)
尝试这样的事情 -
constructor(props) {
super(props);
this.state = {
jsonData: null
};
this.dataSource = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
});
}
render() {
return (
<View style={{flex: 1, paddingTop: 22}}>
{this.state.jsonData &&
<ListView
dataSource={this.dataSource.cloneWithRows(this.state.jsonData)}
renderRow={(rowData) => <Text>{rowData.title}</Text>}
/>}
</View>
);
}
getContractList() {
var url = 'https://facebook.github.io/react-native/movies.json';
fetch(url)
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({isLoading: false, jsonData: responseJson.movies});
})
.catch((error) => {
//console.error(error);
});
}
答案 1 :(得分:-1)
我不是本地反应的专家,但我注意到在fetch('url')
中,URL未在任何地方定义。我建议把Json的URL放在那里。