React Native上的按钮和触摸板会延迟



我打算在我的应用程序中创建一个基本的电子商店,它运行良好。平面列表中的每个项目都有3个按钮(TouchableOpacity(来设置数量。这些按钮非常慢:从时钟到重新渲染之间只有1秒。它看起来像一个长按,但它是一个简单的点击:这是一个向你展示的简单视频

这是详细的代码:

class Shop extends React.Component {
...
selectItem = (item, typeButton) => {
if (item.qte >= 0) {
switch (typeButton) {
case 'plus':
if (parseFloat(item.EshopPrice) <= parseFloat(this.state.score)) {
this.setState({
score: parseFloat(this.state.score).toFixed(2) - parseFloat(item.EshopPrice).toFixed(2),
})
const actionSum = { type: "INCREASE_SUM", value: item }
this.props.dispatch(actionSum)
} else {
this.showToast();
}
break;
case 'minus':
if (this.props.totaleQte > 0) {
item.qte = item.qte - 1
this.setState({
score: Number(parseFloat(item.EshopPrice).toFixed(2)) + this.state.score,
})
const actionSumMoin = { type: "DECREASE_SUM", value: item }
this.props.dispatch(actionSumMoin)
}
break;
case 'plus+':
if (parseFloat(item.EshopPrice) <= parseFloat(this.state.score)) {
item.qte = item.qte + 1
this.setState({
score: parseFloat(this.state.score).toFixed(2) - parseFloat(item.EshopPrice).toFixed(2),
})
const actionSum = { type: "SET_CURRENTSALE", value: item }
this.props.dispatch(actionSum)
} else {
this.showToast();
}
break;
default:
break;
}
}
};
...
render ()
...
return (...)
}

我在同一文件中的一个功能组件中调用这个函数,该文件是flatlit:的renderItem

renderItem = ({ item }) => {
return (
<View style={StylesGift.buttonsContainer}>
{
item.qte === 0 ?
<TouchableOpacity
onPress={() => this.selectItem(item, 'plus+')}>
<Text style={[StylesGift.itemQte, StylesGift.roundItemQte]}>+</Text>
</TouchableOpacity>
:
<View style={StylesGift.buttonsQteContainer}>
<TouchableOpacity onPress={() => this.selectItem(item, 'minus')}>
<Text style={[StylesGift.itemQte, StylesGift.roundItemQte]}>-</Text>
</TouchableOpacity>
<Pressable
onPress={() => this.showModal(true, item)}>
<Text style={StylesGift.itemQte}>{item.qte}</Text>
</Pressable>
<TouchableOpacity onPress={() => this.selectItem(item, 'plus')}>
<Text style={[StylesGift.itemQte, StylesGift.roundItemQte]}>+</Text>
</TouchableOpacity>
</View>
}
</View>
)
}

我认为问题出在setState({score: ...})和向redux调度操作中,因为当我将它们全部删除或删除其中一个时,单击会变得非常快速和流畅。

这是对减速器的处理:

case 'INCREASE_SUM':
const productShopIndex = state.Data.findIndex(item => item.ProductID === action.value.ProductID)
state.Data[productShopIndex].qte = state.Data[productShopIndex].qte + 1
nextState = {
...state,
sum: state.sum + parseFloat(action.value.EshopPrice),
}

return nextState || state
case 'DECREASE_SUM':
nextState = {
...state,
totaleQte: action.value.qte === 0 ? state.totaleQte - 1 : state.totaleQte,
sum: state.sum - parseFloat(action.value.EshopPrice),
}
return nextState || state

实际上,问题是在按下按钮时直接调度全局操作。这样做的副作用是,当你按下+或-时,reducer将需要一些时间来进行计算和更改状态(这就是为什么JS线程被阻塞后会出现延迟的原因(。最简单的解决方案是,对于每个计数器,使增量或减量作为本地状态,并在一些反跳后在useEffect(或componentDidUpdate(内部将该计数与reducer同步。流程为:

  1. 将计数值以本地状态存储在计数器内
  2. 进行大约500ms的反跳,这样当用户在这段时间内按下任何按钮时,它都会忽略最后一次计数,只有在反跳时间后用户离开计数器时才会更新
  3. 并在去抖动后与全局减速器同步

我最近遇到了类似的情况。希望这能有所帮助。

最新更新