【发布时间】:2021-06-28 15:00:43
【问题描述】:
我打算在我的应用程序中创建一个基本的电子商店,它运行良好。 flatlist 中的每个项目都有 3 个按钮(TouchableOpacity)来设置数量。
这些按钮非常慢:时钟和重新渲染之间的 1 秒。它看起来像长按,但很简单:this is a simple video to show you
这是详细的代码:
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 调度操作,因为当我将它们全部删除或删除其中一个时,点击变得非常快速和流畅。
这是对reducer的处理:
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
【问题讨论】:
标签: javascript reactjs react-native performance redux