setState 同步更新
為了提高性能React將setState設(shè)置為批次更新纺棺,即是異步操作函數(shù),并不能以順序控制流的方式設(shè)置某些事件岖研,我們也不能依賴于this.state來計算未來狀態(tài)令杈。
靈感來源
最近接受一個項目掌敬,用的是react-native開發(fā)安卓。遇到 在 this.setState({})
之后的方法已經(jīng)執(zhí)行了蠢熄,但是罩驻,所依賴的數(shù)據(jù)卻沒有更新
具體如圖 ↓
失敗的效果圖
影響的具體原因就是
setState
是異步操作的。
我的部分出現(xiàn)bug的代碼如下
constructor (props) {
super (props)
this.state = {
buyingGoodsItemData: [], // 用戶購買的商品數(shù)據(jù)
totalPrice: 0, // 用戶所有購買商品的總價格
}
}
/**
* 點擊商品列表某項觸發(fā)的方法
* @param {形參} el 當(dāng)前點擊的那個商品數(shù)據(jù)
*/
onMyPressButton (el) {
this.setState({
buyingGoodsItemData: [...this.state.buyingGoodsItemData, el]
})
this.calculateCountAndPrice()
}
/**
* 計算價格的方法
*/
calculateCountAndPrice = () => {
let tempTotalPrice = 0
let tempBuyingGoodsItemData = this.state.buyingGoodsItemData
for (let i = 0; i < tempBuyingGoodsItemData.length; i++) {
tempTotalPrice += tempBuyingGoodsItemData[i].price * tempBuyingGoodsItemData[i].count
}
this.setState({
totalPrice: tempTotalPrice
})
}
render() {
return (
<View style={styles.container}>
<ScrollView>
<View style={styles.goodsWrapper}>
{
this.state.goodListData.map(el => {
return (
<GoodsList item={el} key={el.id} onHandleClick={this.onMyPressButton.bind(this, el)} />
)
})
}
</View>
</ScrollView>
<View style={styles.totalPriceWrapper}>
<Text style={styles.totalPrice}>合計:¥{this.state.totalPrice}</Text>
</View>
</View>
)
}
修復(fù)后的
// 只在這里添加了护赊,可能不是最好的方法惠遏。
/**
* 點擊商品列表某項觸發(fā)的方法
* @param {形參} el 當(dāng)前點擊的那個商品數(shù)據(jù)
*/
async onMyPressButton (el) {
const newArr = this.state.buyingGoodsItemData.filter(item => {
return item.id === el.id
})
if (newArr.length === 0) {
await this.setState({
buyingGoodsItemData: [...this.state.buyingGoodsItemData, el]
})
this.calculateCountAndPrice()
}
}
成功的效果
無基礎(chǔ)接收react-native
,真的好吃力骏啰。
記錄于 2019-5-6