英文:
How to avoid reinitializing a useState variable in React Native
问题
I am working on a music app in React Native. This page will be re-opened several times, but I do not want the trackList to reset to [] every time the page is re-rendered, but instead to retain its values. I have included a simplified version of my code:
let existsTrackListener = false;
export default function Host({ navigation }) {
const [trackList, setTrackList] = useState([]);
if (!existsTrackListener) {
setTrackListener(roomID, (t) => {
if (t != null) {
const newArray = [...trackList, t.name];
setTrackList(newArray);
}
});
existsTrackListener = true;
}
return (
<View style={styles.container}>
<FlatList
data={trackList}
renderItem={({ item }) => <Text style={styles.item}>{item}</Text>}
/>
</View>
);
}
(Note: I retained the code as-is and provided the translation in your requested format.)
英文:
I am working on a music app in React Native. This page will be re-opened several times, but I do not want the trackList to reset to [] everything the page is re-rendered, but instead to retain its values. I have included a simplified version of my code:
let existsTrackListener = false;
export default function Host({ navigation }) {
const [trackList, setTrackList] = useState([]);
if (!existsTrackListener) {
setTrackListener(roomID, (t) => {
if (t != null) {
const newArray = [...trackList, t.name];
setTrackList(newArray);
}
});
existsTrackListener = true;
}
return (
<View style={styles.container}>
<FlatList
data={trackList}
renderItem={({ item }) => <Text style={styles.item}>{item}</Text>}
/>
</View>
);
}
答案1
得分: 2
如果你希望在应用程序运行时保持状态,你可以使用React上下文。
如果你希望将状态持久化存储,以便在下次启动应用程序时可用,考虑使用数据库。有许多可用的数据库,例如SQLite、Realm、Firebase(云选项)。
英文:
If you want the state to live while the app is running, you can can use react context.
If you want to persist the state on storage so it's available on the next launch of your app, consider using database. There are many databases available, such as SQLite, Realm, Firebase (cloud option).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论