【发布时间】:2019-01-26 20:43:30
【问题描述】:
我正在使用 React Native 构建一个电子商务应用程序。我遇到了一个问题。在“购物篮”页面中,我想显示商品的总价。
我在开始时将状态 totalPrice 设置为 0,当我在平面列表中显示每个项目时,我想更新 totalPrice (totalPrice = totalPrice + 项目价格 * 数量)
我的代码:
class Basket extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
totalPrice: 0,
}
}
componentDidMount(){
return fetch(...)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.records,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
render() {
if(this.state.isLoading){
return(
<View>
<ActivityIndicator/>
</View>
)
}
return (
<View style={{ flex: 1}}>
<ScrollView>
<FlatList
data={this.state.dataSource}
numColumns={1}
renderItem={({item}) => //displaying the items
//below i want to update totalPrice but it didn't work
this.setState({
totalPrice : this.state.totalPrice + item.quantity *
item.price,
});
}
/>
</ScrollView>
<View>
<Text> {this.state.totalPrice} </Text>
</View>
</View>
);
}
}
【问题讨论】:
标签: reactjs react-native reactive-programming expo mobile-development