Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用异步存储响应本机保存更改开关_Reactjs_React Native_Switch Statement_Asyncstorage - Fatal编程技术网

Reactjs 使用异步存储响应本机保存更改开关

Reactjs 使用异步存储响应本机保存更改开关,reactjs,react-native,switch-statement,asyncstorage,Reactjs,React Native,Switch Statement,Asyncstorage,我是React Native的新手,我的开关有问题,我想保存更改,暗模式和开关,当我关闭应用程序并返回时,我的更改应该保存。当我关闭应用程序时,我的开关回到第一个位置,黑暗模式不工作。我知道我做错了什么,但我没有使用移动应用程序,这是我第一次,我不知道如何在这个应用程序中使用异步存储来工作。有人能帮我解决这个问题吗 import React, { createContext, useState, useEffect } from 'react'; import { AsyncStorage }

我是React Native的新手,我的开关有问题,我想保存更改,暗模式和开关,当我关闭应用程序并返回时,我的更改应该保存。当我关闭应用程序时,我的开关回到第一个位置,黑暗模式不工作。我知道我做错了什么,但我没有使用移动应用程序,这是我第一次,我不知道如何在这个应用程序中使用异步存储来工作。有人能帮我解决这个问题吗

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,{createContext,useState,useffect}来自'React';
从“react native”导入{AsyncStorage};
导出常量DarkModeContext=createContext();
导出默认函数DarkModeContextProvider(props){
const[switchMode,setSwitchMode]=使用状态(false);
useffect(()=>{
设switch1=switchMode;
AsyncStorage.setItem('switch1',JSON.stringify(switch1));
});
常量开关this=()=>{
设置开关模式(!开关模式);
};
返回(
{props.children}
);
}
下一个组成部分:

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>
  );
};
import React,{useState,useContext}来自“React”;
从“react native”导入{View、ScrollView、TouchableOpacity、Text、AsyncStorage};
从“react native paper”导入{List};
从“./BackgroundImage”导入BackgroundImage;
从“./Clock”导入时钟;
从“/TabIcon”导入TabIcon;
从“/AddButton”导入AddButton;
从“./app context”导入{DarkModeContext};
常量主屏幕=()=>{
const{switchMode}=useContext(暗模式上下文);
displayData=async()=>{
试一试{
让switch1=等待AsyncStorage.getItem('switch1',函数(err,switch1){
JSON.parse(switch1)
}
)
返回开关1
}
捕获(错误){
返回错误
}
}
返回(
任务列表
单击显示数据
);
};

您正在从已弃用的“react native”导入异步存储 使用
@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)


react native的版本是什么?在主屏幕中,调用AsyncStorage并在useEffect下使用useState设置暗模式变量。ComponentDidMount应该触发异步存储。正如我所看到的,问题是您没有在主屏幕加载上设置暗模式变量。