我很难从某些服务器上获取数据以响应本机。 首先,我使用Web API。在这种情况下,我使用Axios(我认为更好用,也许是错误的!) 现在我无法显示此数据,或者可能无法获取,我不知道,请帮助我。
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import ajax from '../ajax';
import Deallist from './deallist';
import axios from 'axios';
const API = 'https://bakesaleforgood.com'
const DEFAULT_QUERY = '/api/deals/'
class app extends Component {
componentDidMount() {
this.setState({ isLoading: true })
axios.get(API + DEFAULT_QUERY)
.then(result => this.setState({
deals: result.data.deals,
isLoading: false
}))
.catch(error => this.setState({
error,
isLoading: false
}))
// const deals = await ajax.fetchInitialDeals();
// this.setState({deals:deals})
}
constructor(props) {
super(props);
this.state = {
deals: [],
isLoading: false,
error: null,
};
}
render() {
return (
<View style={styles.container}>
{
this.state.deals.length > 0
? < Deallist deals={this.state.deals}></Deallist>
: <Text style={styles.header}> Bakesale </Text>
}
</View>
);
};}const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
header: {
fontSize: 40,
}})export default app;
deallist.js:
import React, { Component } from 'react';
import { View, Text, StyleSheet,FlatList } from 'react-native';
import PropTypes from 'prop-types';
import DealItem from './dealitem';
class Deallist extends Component {
static propTypes = {
deals: PropTypes.array.isRequired,
}
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<View style={styles.list}>
<FlatList
data={this.props.deals}
renderItem={({ item }) => <DealItem deal={item}/>}
/>
</View>
);
}
}
const styles = StyleSheet.create({
list: {
backgroundColor: '#eee',
flex: 1,
width: '100%',
paddingTop: 50,
}
})
export default Deallist;
dealitem.js
import React, { Component } from 'react';
import { View, Text,StyleSheet,Image } from 'react-native';
import PropTypes from 'prop-types';
class DealItem extends Component {
static propTypes={
deal:PropTypes.object.isRequired,
}
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<View>
<Image
source={{uri: this.props.deal.media[0]}}
style={styles.image}
></Image>
</View>
);
}
}
const styles=StyleSheet.create({
image:{
height:150,
width:'100%',
}
})
export default DealItem;
我收到state.deals.lenght的类型错误
答案 0 :(得分:0)
数据对象没有deals
属性,它是一个对象数组。改用result.data
。
componentDidMount = () => {
this.setState({ isLoading: true }); // you set this true by default, instead of setting it here.
axios.get(API + DEFAULT_QUERY)
.then(result => this.setState({
deals: result.data,
isLoading: false
}))
.catch(error => this.setState({
error,
isLoading: false
}))
}
答案 1 :(得分:0)
问题在这里:
this.state.deals.length > 0 ? < Deallist deals={this.state.deals}></Deallist> : <Text style={styles.header}> Bakesale </Text>
您有2种方法:
(((type.this.stat.deals!='undefined')&&(this.state.deals.length> 0))
componentWillMount(){ this.setState({deals:[]}); }
axios是一个很好的软件包,但是您也可以使用ES6中存在的访存功能