我正在使用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>
)
}
答案 0 :(得分:6)
您可能想将extraData
道具添加到平板列表中:
<FlatList
renderItem={this._renderItem}
keyExtractor={ (item,index) => index.toString() }
data={this.state.data}
extraData={this.state}
/>
FlatList extraData:
一个标记属性,用于告诉列表重新呈现(因为它实现了PureComponent)。如果您的renderItem,Header,Footer等函数中的任何一个都依赖于数据道具之外的任何东西,请将其粘贴在这里并一成不变地对待。
找到here