AsyncStorage用于在React native中存储themeColor

hm2xizp9  于 2023-10-22  发布在  React
关注(0)|答案(1)|浏览(120)

我是新的在这个主题(数据存储在CockStorage)我想存储我的主题颜色在CockStorage,因为当用户关闭应用程序,他们将保持不变,因为他们选择。我能够改变点击主题,但有一些点击问题.
我必须点击两次才能改变主题(eq.:如果有光的主题,那么我必须点击像光到黑暗,再轻轻,那么我就能够得到黑暗的主题,如果有黑暗的主题,那么我必须点击两次改变像黑暗到光明到黑暗的主题,那么我会得到光明的主题
这是我的Context.js文件

import React, {createContext, useEffect, useState} from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';

const Context = createContext();

export const TProvider = ({children}) => {
  const [theme, setTheme] = useState('light');

  const toggleTheam = async () => {
    const DataClr = await AsyncStorage.getItem('Color');

    setTheme(theme === 'light' ? 'dark' : 'light');

    AsyncData();
  };

  const AsyncData = async () => {
    await AsyncStorage.setItem('Color', theme);
  };

  return (
    <Context.Provider value={{theme, toggleTheam, setTheme}}>
      {children}
    </Context.Provider>
  );
};

export default Context;

这是我的First.js文件,我在Press上更改了主题

import React, {useContext, useEffect} from 'react';
import {View, Button, Text} from 'react-native';
import Context from './Context';
import AsyncStorage from '@react-native-async-storage/async-storage';

const First = ({navigation}) => {
  const {theme, toggleTheam, setTheme} = useContext(Context);

  useEffect(async () => {
    const Data = await AsyncStorage.getItem('Color');
    if (Data) {
      setTheme(Data);
    }
  }, []);

  console.log('Theme==>', theme);

  return (
    <View
      style={{
        height: '100%',
        padding: 20,
        backgroundColor: theme === 'light' ? '#fff' : '#000',
      }}>
      <Text
        style={{
          textAlign: 'center',
          color: theme === 'light' ? '#000' : '#fff',
        }}>
        First Screen
      </Text>
      <Button title="Change Color" onPress={toggleTheam} />
      <Button
        title="Go to next Screen"
        onPress={() => {
          navigation.navigate('Second');
        }}
      />
    </View>
  );
};
export default First;

我试图将我的主题颜色存储在Context.js文件中,但当我刷新应用程序时,我无法获得该主题

wrrgggsh

wrrgggsh1#

我已经用这个解决了这个功能。我可以将useContext数据存储在asyncStorage中。

const [theme, setTheme] = useState('light');
const [clr, setCle] = useState('');

useEffect(() => {
  const MainTheme = async () => {
    try {
      const storedTheme = await AsyncStorage.getItem('Color');
      if (storedTheme !== null) {
        setTheme(storedTheme);
      }
    } catch (error) {
      console.error(error);
    }
  };

  MainTheme();
}, []);

const toggleTheam = () => {
  setTheme(value => {
    const newTheme = value === 'light' ? 'dark' : 'light';
    SetData(newTheme);
    return newTheme;
  });
};

const SetData = async newTheme => {
  try {
    await AsyncStorage.setItem('Color', newTheme);
  } catch (error) {
    console.error(error);
  }
};

相关问题