异步存储将主题存储在React本机中



我已经使用上下文设置了主题,但我想在用户重新启动应用程序后保存主题。我是数据存储的新手,所以我需要一些帮助来了解如何在异步存储中为特定情况编写此代码,因为我对如何使其工作有点困惑。非常感谢。(我已经清理了很多代码,只包括相关的东西,所以这就是为什么它看起来很瘦的原因(

在App.js下

import ThemeContext, {themes} from './contexts/ThemeContext';
const [selectedTheme, setSelectedTheme] = useState(themes.arctic)
const changeTheme = (theme) =>{
if (theme === "dark"){
setSelectedTheme(themes.dark)} 
else if (theme === "light") {
setSelectedTheme(themes.light)
}
else if (theme === "red") {
setSelectedTheme(themes.red)
}
<ThemeContext.Provider value={{selectedTheme, changeTheme}}>
<....>
<Stack.Screen name="Settings" component={Settings}/>

在设置下(如果需要此代码,这是我调用changeTheme函数的地方(

const handlePress = (theme) => {
changeTheme(theme)}

<ThemeBadge color="white" onPress={()=>handlePress("light")}/>
<ThemeBadge color="black" onPress={()=>handlePress("dark")}/>
<ThemeBadge color="red" onPress={()=>handlePress("red")}/>

在使用Expo时,请安装expo-secure-store。让我们使用自定义挂钩来轻松管理应用程序主题偏好。

import * as SecureStore from "expo-secure-store";
import { useeEffect, useState } from "react";
function useAppTheme() {
const [theme, setTheme] = useTheme("light");
async function updateTheme(key = "theme", value) {
await SecureStore.setItemAsync(key, String(value).toString());
}
async function getTheme(key = "theme") {
let result = await SecureStore.getItemAsync(key);
if (result) {
setTheme(result);
} else {
console.error("App could not get theme.");
}
}
useEffect(() => getValueFor("theme"), []);
return { theme, getTheme, updateTheme };
}
export default useAppTheme;

稍后在代码中,使用钩子

const App = ()=>{
const {theme, updateTheme} = useAppTheme
const changeTheme = async (theme) =>{
if (theme === "dark"){
await updateTheme("theme",themes.dark)
setSelectedTheme(themes.dark)} 
else if (theme === "light") {
await updateTheme("theme",themes.light)
setSelectedTheme(themes.light)
}
else if (theme === "red") {
await updateTheme("theme",themes.red)
setSelectedTheme(themes.red)
}
<ThemeContext.Provider value={{selectedTheme, changeTheme}}>
<....>
<Stack.Screen name="Settings" component={Settings}/>

}

最新更新