我正在尝试在React Native中使用“ Axios”从本地服务器上的API获取数据,但没有从API获取数据并显示“ TypeError:undefined不是对象(评估'allRowIDs.length')”中的数据模拟器。
这是我的代码:
import React, { Component } from 'react';
import { StyleSheet, ActivityIndicator, ListView, Text, View, Alert } from 'react-native';
import axios from 'axios';
export default class pageOne extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
}
}
async componentDidMount(){
try{
await axios.post('http://192.168.38.230/reactTest/list.php')
.then(response => {
console.log(response);
this.setState({isLoading: false, dataSource: response})})
.catch(err => console.log(err));
} catch(error){
console.log('Fetch Error:', error)
}
}
render() {
if (this.state.isLoading) {
return (
<View>
<ActivityIndicator />
</View>
);
}
return (
<ListView
dataSource={this.state.dataSource}
renderSeparator= {this.ListViewItemSeparator}
enableEmptySections = {true}
renderRow={(rowData) => <Text style={styles.rowViewContainer}
onPress={this.GetItem.bind(this, rowData.cl_name)} >{rowData.cl_name}</Text>}
/> );}}
这是api数据
[{"id":"1","cl_name":"test11"},{"id":"2","cl_name":"test12"},{"id":"3","cl_name":"test13"},{"id":"4","cl_name":"test14"}]
答案 0 :(得分:1)
您需要更新isLoading
async componentDidMount(){
try{
await axios.post('http://IP ADDRESS/reactTest/list.php')
.then(response => {
console.log(response);
this.setState({isLoading: false, dataSource: response})})
.catch(err => console.log(err));
} catch(error){
console.log('Fetch Error:', error)
}
}
答案 1 :(得分:1)
好的,我这样做可以解决我的问题-
import React, { Component } from 'react'
import { StyleSheet, ActivityIndicator, ListView, Text, View, Alert } from 'react-native'
import axios from 'axios'
class axioslist extends Component {
constructor(props) {
super(props);
this.state = {
posts:[]
}
}
componentDidMount(){
axios.get('http://IP address/reactTest/list.php')
.then(res => {
console.log(res)
this.setState({
posts: res.data.slice(0,10)
})
})
}
render() {
const { posts } = this.state;
const postList = posts.length ? (
posts.map(post =>
{
return(
<Text key={post.id}>
{post.cl_name}
</Text>
)
})
) : (<Text>No data yet.</Text>)
return (
<View>
<Text>{postList} </Text>
</View> );
}}
export default axioslist
答案 2 :(得分:0)
this.state = {
dataSource: null,
}
componentDidMount(){
return axios.post('http://IP ADDRESS/reactTest/list.php')
.then(response => this.setState({ dataSource: response, isLoading: false)
.catch(err => console.log(err));
}