我正在使用FlatList,它正确显示所有内容。
但是当我更新产品数量时,它只会增加总量,但FlatList的renderItem没有任何变化。
当我按下加号按钮时,总金额会改变,但产品数量不会改变。
如何更新产品数量?当总金额更新时,为什么不更改FlatList
项目的数量?
我的代码: -
constructor(props) {
super(props);
this.state = {
data:[
{id:4, productName:'Product 4', shortDescription:'shortDescription 4', qty:1, price:500 },
{id:5, productName:'Product 5', shortDescription:'shortDescription 5', qty:1, price:1000},
{id:6, productName:'Product 6', shortDescription:'shortDescription 6', qty:1, price:1000},
],
};
}
_addQty = (index) => {
var data = this.state.data;
data[index].qty = data[index].qty + 1;
this.setState(data:data);
}
_getTotalPrice = () => {
var total = 0;
for (var i = 0; i < this.state.data.length; i++) {
total += this.state.data[i].qty * this.state.data[i].price;
};
return total;
}
_renderItem = ({item, index}) => {
var imageCloseWidth = 20;
var margin = 5;
var subViewWidth = width-(margin*3);
return <View key={index} style={{ marginBottom: margin, marginHorizontal: margin, marginTop: index==0?margin:0}}>
<View style={{flexDirection: 'row', flex:1}}>
<View style={{justifyContent: 'space-between', width:subViewWidth+imageWidth}}>
<View>
<TouchableOpacity style={{position: 'absolute', right: 0}}>
<View><Image style={{height:imageCloseWidth, width:imageCloseWidth, tintColor: '#888888'}} source={MyConstants.imgClose} /></View>
</TouchableOpacity>
<Text style={[styles.txtProductName, {width:subViewWidth}]}>{item.productName}</Text>
<Text style={styles.txtSortDesc}>{item.shortDescription}</Text>
</View>
<View style={{flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginTop:5}}>
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<TouchableOpacity>
<View><Image style={{height:20, width:20, tintColor: item.qty>1 ? "#888888":"#BBBBBB"}} source={MyConstants.imgMinus} /></View>
</TouchableOpacity>
<Text style={{marginHorizontal: 5, fontSize: 18}}>{item.qty}</Text>
<TouchableOpacity
onPress={ ()=> {
this._addQty(index);
}}>
<View><Image style={{height:20, width:20, tintColor: '#888888'}} source={MyConstants.imgPlush} /></View>
</TouchableOpacity>
</View>
<Text style={{marginHorizontal: 5, fontSize: 18}}>{item.price}</Text>
</View>
</View>
</View>
</View>
}
render() {
return (
<View style={styles.container}>
<FlatList
renderItem={this._renderItem}
keyExtractor={ (item,index) => index.toString() }
data={this.state.data} />
<View style={{flexDirection:'row', justifyContent: 'space-between'}}>
<Text style={{flex:3, fontSize: 18}}>Total amount</Text>
<Text style={{flex:1, fontSize: 18, textAlign:'right'}}>{this._getTotalPrice()}</Text>
</View>
</View>
)
}
您可能希望将extraData
道具添加到平面列表中:
<FlatList
renderItem={this._renderItem}
keyExtractor={ (item,index) => index.toString() }
data={this.state.data}
extraData={this.state}
/>
而额外Flatlist;
用于告知列表重新呈现的标记属性(因为它实现了PureComponent)。如果你的任何renderItem,Header,Footer等函数依赖于数据道具之外的任何东西,请将其粘贴在此处并进行不可变处理。
找到它here