React Native save change switch with Async Storage

问题描述 投票:0回答:1

我是React Native的新手,我在使用Switch时遇到问题,我想保存更改,暗模式和Switch,当我关闭应用程序并返回时,应保存我的更改。当我关闭应用程序时,我的开关返回到第一位置,并且暗模式不起作用。我知道我做错了什么,但是我没有移动应用程序,这是我第一次,而且我不知道如何在此应用程序中使用AsyncStorage来解决此问题。有人可以帮我解决这个问题吗?

import React, { createContext, useState, useEffect } from 'react';
import { AsyncStorage } from 'react-native';

export const DarkModeContext = createContext();

export default function DarkModeContextProvider(props) {
  const [switchMode, setSwitchMode] = useState(false);

  useEffect(() => {
    let switch1 = switchMode;
    AsyncStorage.setItem('switch1', JSON.stringify(switch1));
  });

  const SwitchThis = () => {
    setSwitchMode(!switchMode);
  };

  return (
    <DarkModeContext.Provider
      value={{
        switchMode,
        SwitchThis
      }}
    >
      {props.children}
    </DarkModeContext.Provider>
  );
}

和下一个组件:

import React, { useState, useContext } from 'react';
import { View, ScrollView, TouchableOpacity, Text, AsyncStorage } from 'react-native';
import { List } from 'react-native-paper';
import BackgroundImage from './BackgroundImage';
import Clock from './Clock';
import TabIcon from './TabIcon';
import AddButton from './AddButton';
import { DarkModeContext } from './app-context';

const HomeScreen = () => {
  const { switchMode } = useContext(DarkModeContext);

  displayData = async () => {
    try {
      let switch1 = await AsyncStorage.getItem('switch1', function (err, switch1) {
        JSON.parse(switch1)
      }
)
      return switch1
    }
    catch (error) {
      return error
    }
  }

  return (
    <View
      style={{
        flex: 1,
        backgroundColor: !switchMode ? 'white' : '#353535'
      }}
    >
      <BackgroundImage fabButton={<AddButton/>}>
        <Clock />
      </BackgroundImage>
      <ScrollView>
        <List.Section>
          <List.Subheader style={{ color: !switchMode ? 'black' : 'white' }}>
            Task List
          </List.Subheader>
          <TouchableOpacity onPress={displayData}>
            <Text>Click displayData</Text>
          </TouchableOpacity> 
        </List.Section>
      </ScrollView>
    </View>
  );
};
reactjs react-native switch-statement asyncstorage
1个回答
0
投票

您正在从'react-native'导入AsyncStorage,该版本已弃用使用@react-native-community/react-native-async-storage

npm i @react-native-community/react-native-async-storage

并且在主屏幕上,您没有调用函数displayData(),因此应该如何在不调用函数的情况下显示数据。

而且我建议为异步存储进行读写操作提供单独的功能,这将帮助您减少代码和时间。

喜欢这个:

let  storeData=(name, obj)=> {

    return new Promise((resolve,reject)=>{

            let jsonOfItem = JSON.stringify(obj)
            AsyncStorage.setItem(name, jsonOfItem).then(r=>resolve(jsonOfItem))
            .catch(e=>reject(e))

    })

  }

let  readData=(name)=> {

    return new Promise((resolve,reject)=>{
            //we want to wait for the Promise returned by AsyncStorage.setItem()
            //to be resolved to the actual value before returning the value
            AsyncStorage.getItem(name).then(r=> resolve(JSON.parse(r)) )
            .catch(e=>reject(e))

    })

  }

//Now you can just read write easily in async function like this:

let fetchedData = await  readData("key")

//and for storing data.

storeData("key",object)

© www.soinside.com 2019 - 2024. All rights reserved.