在我添加 2
useEffects
从我的 sqlite 数据库获取数据后,我的 React-Native 似乎非常慢。它使应用程序变得如此缓慢,以至于几乎无法响应用户输入。我该如何解决这个问题?
import { SafeAreaView } from "react-native-safe-area-context";
import { Pressable, View } from "react-native";
import { Header, AddMeal, TabBar, Rings4, RecentMeals } from "../components";
import { COLORS } from "../constants/colors";
import DraggableFlatList, { ScaleDecorator } from "react-native-draggable-flatlist";
import { useEffect, useState } from "react";
import * as SQLite from "expo-sqlite";
const widgetsEnum = {
"rings4": 0,
"recentmeals": 1,
}
const App = () => {
function getWidget(type){
switch(type){
case 0: return(<Rings4 macros={macros} />);
case 1: return(<RecentMeals />);
}
return(<></>);
}
const renderItem = ({item, drag, isActive}) => {
return (
<ScaleDecorator
activeScale={1.05}
>
<Pressable
onLongPress={drag}
disabled={isActive}
>
{ getWidget(item.type) }
</Pressable>
</ScaleDecorator>
)
}
const [widgets, setWidgets] = useState(
[
{type: widgetsEnum.rings4, id: 1},
{type: widgetsEnum.recentmeals, id: 2},
{type: widgetsEnum.rings4, id: 3},
{type: widgetsEnum.rings4, id: 4},
]
)
const db = SQLite.openDatabase('db1.db');
const date = `${new Date().getDate()}_${new Date().getMonth() + 1}_${new Date().getFullYear()}`
const [sqlData, setSqlData] = useState([]);
const [macros, setMacros] = useState({
protein: 0,
calories: 0,
fats: 0,
sugar: 0,
})
useEffect(() => {
db.transaction(tx => {
tx.executeSql(`SELECT * FROM Meals${date}`, null,
(txObj, { rows: { _array } }) => {
setSqlData(_array);
})
})
}, [db]);
useEffect(() => {
let newMacros = {
protein: 0,
calories: 0,
fats: 0,
sugar: 0
}
sqlData.forEach((element) => {
newMacros.protein += element.protein;
newMacros.calories += element.calories;
newMacros.fats += element.fats;
newMacros.sugar += element.sugar;
})
setMacros(newMacros);
}, [sqlData])
return (
<SafeAreaView style={{
flex: 1,
backgroundColor: COLORS.background,
}}>
<Header />
<DraggableFlatList
style={{ paddingHorizontal: 16, paddingVertical: 12, marginBottom: 134 }}
data={widgets}
onDragEnd={({ data }) => setWidgets(data)}
renderItem={renderItem}
ItemSeparatorComponent={() => <View style={{ height: 14 }}/>}
keyExtractor={(widget) => widget.id}
showsVerticalScrollIndicator={false}
/>
<AddMeal />
<TabBar />
</SafeAreaView>
)
}
export default App;
我尝试计算从数据库检索数据的
useEffect
内部的宏,但这导致了无限的重新渲染循环。
解决方案是不在组件内打开我的数据库:facepalm: