解决react-native中setState同步更新
2019-05-06 本文已影响0人
程序猿阿峰
setState 同步更新
为了提高性能React将setState设置为批次更新,即是异步操作函数,并不能以顺序控制流的方式设置某些事件,我们也不能依赖于this.state来计算未来状态。
灵感来源
最近接受一个项目,用的是react-native开发安卓。遇到 在 this.setState({})
之后的方法已经执行了,但是,所依赖的数据却没有更新
具体如图 ↓
影响的具体原因就是
setState
是异步操作的。
我的部分出现bug的代码如下
constructor (props) {
super (props)
this.state = {
buyingGoodsItemData: [], // 用户购买的商品数据
totalPrice: 0, // 用户所有购买商品的总价格
}
}
/**
* 点击商品列表某项触发的方法
* @param {形参} el 当前点击的那个商品数据
*/
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>
)
}
修复后的
// 只在这里添加了,可能不是最好的方法。
/**
* 点击商品列表某项触发的方法
* @param {形参} el 当前点击的那个商品数据
*/
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()
}
}
成功的效果
无基础接收react-native
,真的好吃力。
记录于 2019-5-6