【发布时间】:2020-08-24 22:42:52
【问题描述】:
我正在使用异步函数从 API 中检索折扣,然后在购物车中使用该折扣, 每当在 render 方法中调用打折购物车功能时,它就会开始自我重复,但是当通过单击事件上的按钮执行调用时,它会完美运行。
discountedCart = async (id, qty) => {
console.log("Discounted Cart");
const response = await fetch(
"https://usautoparts-erp.azurewebsites.net/Api/Cart",
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({ products: [id] }),
}
);
const data = await response.json();
console.log(data);
this.setState({
DiscountData: data,
});
let D = "No discount";
const discounts = data.filter((item) => item.quantity <= qty);
console.log("selected");
console.log(discounts);
if (discounts[discounts.length - 1].amount != null) {
D = discounts[discounts.length - 1].amount;
console.log("Amount:" + D);
} else if (discounts[0].percentage != null) {
D = discounts[0].percentage;
console.log("percentage:" + D);
}
console.log("Discount:" + D);
this.setState({
rough: D,
});
return D;
};
render() {
return (
<>
<Button title="Clear Cart" onPress={() => this.ClearCart()} />
<FlatList
data={this.state.p}renderItem={({ item }) =>
{const a = this.discountedCart(item.id,item.Qty);
return(
<View style={{ flex: 1, flexDirection: "column", margin: 1 }}>
<Text>{item.id}</Text>
</View>
</View>
)}
}
numColumns={1}
keyExtractor={item => item.id.toString()}
/>
</>
);
}
}
【问题讨论】: