1.一开始怎么也调不出来,原来要求dataSource必须是一个数组。
json数据 (HOT_SALE_URl.json),自己可以把这个数据放在网络上或者自己的服务器以json形式传过来就可以了。由于私人服务器不便公开,以下是获取的json数据格式。可以自己网上找一个json当测试。
{
"data": {
"promote_goods": [
{
"id": 3584,
"goodsSn": "550500GG002",
"image": "http://image.002_0.jpg",
"shopPrice": "182.00",
"goods_id": 3584,
"brief": null,
"img": {
"thumb": "http://image.ka002_0.jpg",
"url": "http://imag0.jpg",
"small": "http://im_0.jpg"
},
"market_price": "0.0",
"name": "遮阳罩高顶老款 豪沃",
"promote_price": "",
"shop_price": "182.00",
"listPrice": "182.00"
},
{
"id": 4352,
"goodsSn": "351300GG021",
"image": "http://image.kach0.jpg",
"shopPrice": "211.00",
"goods_id": 4352,
"brief": null,
"img": {
"thumb": "http://image.k021_0.jpg",
"url": "http://image.1_0.jpg",
"small": "http://im0.jpg"
},
"market_price": "0.0",
"name": "储气筒-带隔板(20+5L) 豪沃",
"promote_price": "",
"shop_price": "211.00",
"listPrice": "211.00"
},
]
},
"status": {
"succeed": 1,
"error_code": null,
"error_desc": null
},
"paginated": null,
"session": null
}
list.js比较简单,只写了这个js就可以了
'use strict ';
import React,{Component} from 'react';
import {
View,
Text,
StyleSheet,
TouchableHighlight,
ListView,
Image,
TouchableOpacity
} from 'react-native';
let HOT_SALE_URl='https://m-XXdata'; //私人服务器数据不便公开,就是以上的json数据
class List extends Component{
constructor(props){
super(props);
this.state={
dataSource:new ListView.DataSource({
rowHasChanged:(row1,row2) => row1 !==row2
}),
loaded:false,
}
}
界面渲染
render(){
return(
<View style={styles.containers}>
<TouchableHighlight underlayout='#4169e1'
onPress={this._pressBack.bind(this)}> //此处页面导航返回用,不需要可省略
<Text > 返回首页</Text>
</TouchableHighlight>
<ListView //关键在这里,绑定数据dataSource,渲染界面renderRow
dataSource={this.state.dataSource}
renderRow={this._renderRow.bind(this)}
style={styles.listView}
/>
</View>
)
}
componentDidMount(){
//组件加载完成,开始加载网络数据
this.fetchData();
}
获取网络数据
fetchData(){
fetch(HOT_SALE_URl)
.then((response) =>{
return response.json()
})
.then((responseData) =>{
console.log("responseData.data=="+JSON.stringify(responseData.data.promote_goods))
this.setState({
dataSource:this.state.dataSource.cloneWithRows(responseData.data.promote_goods),
loaded:true,
})
})
.done();
}
_renderRow(item){
return(
<TouchableOpacity onPress={() => this._onPressItem()}>
<View>
<View>
<Text style={styles.listImgStyle}>item.id==={item.id} </Text>
</View>
<Image
source={{uri:item.img.thumb}}
style={styles.listImgStyle}
/>
</View>
</TouchableOpacity>
)
}
const styles=StyleSheet.create({
//样式此处省略,自己根据需要补充就可以了
)}
module.exports=List;
自己钻的比较低级的一个错误:
1.怎么都报无法识别_renderRow方法中的item.id.原来是我像下图这样,数据绑定的data不是一个数组。
responseData.data.promote_goods才是一个数组。,像下图这样就出来了