还原到屏幕时,异步存储不起作用。多集/获取。反应本机

时间:2020-07-25 16:55:01

标签: javascript reactjs react-native

我正在使用堆栈导航器显示两个屏幕。在此文件Macros.js中,我按照函数所示设置了宏目标,并将其与异步存储方法一起存储。但是,当我返回主屏幕并返回到macros.js屏幕时,该值返回为0。

我的构造函数:

constructor(props) {
    super(props);
    this.getData();
    
    this.state = {
      isLoading: true,
      dataSource: null,
      totalCalsSet: 0,
      showModal: false,
      showModal2: false,
      UsedDailyCalories: 0,
      UsedDailyFat: 0,
      UsedDailyCarbs: 0,
      UsedDailyProtein: 0,
      CalsFatInput: 0,
      CalsProteinInput: 0,
      CalsCarbsInput: 0,
      CaloriePercentage: 0,
      FatPercentage: 0,
      CarbPercentage: 0,
      ProteinPercentage: 0,
      FatSet: 0,
      CarbsSet: 0,
      ProteinSet: 0,
    };
  }   

设置宏功能

setMacros = async (ProteinInput, FatInput, CarbsInput) => {
        let CalsProteinInput = ProteinInput * 4;
        let CalsFatInput = FatInput * 9;
        let CalsCarbsInput = CarbsInput * 4;
        let totalCalsSet = CalsCarbsInput + CalsFatInput + CalsProteinInput;
    
        this.setState({
          totalCalsSet: totalCalsSet,
          CalsProteinInput: ProteinInput,
          CalsFatInput: CalsFatInput,
          CalsCarbsInput: CalsCarbsInput,
          showModal: false,
          FatSet: FatInput,
          CarbsSet: CarbsInput,
          ProteinSet: ProteinInput,
        });
    
        const firstPair = [
          "totalCalsSet",
          JSON.stringify(this.state.totalCalsSet),
        ];
        const secondPair = ["FatSet", JSON.stringify(FatSet)];
        const thirdPair = ["ProteinSet", JSON.stringify(ProteinSet)];
        const fourthPair = ["CarbsSet", JSON.stringify(CarbsSet)];
    
        try {
          this.setState({});
          var setValues = [firstPair, secondPair, thirdPair, fourthPair];
          AsyncStorage.setItem("DATA_KEY", JSON.stringify(setValues));
        } catch (error) {
          console.log(error);
        }
      };
    

我的get Data方法

 getData = async () => {
        try {
          AsyncStorage.multiGet(["key1", "key2"]).then((response) => {});
        } catch (e) {
          // read error
        }

  };

我假设我以通常的方式访问它们?如下:

  <Text>Daily Calories: {this.state.totalCalsSet} </Text>

0 个答案:

没有答案