【问题标题】:How to Update React Native Functional Component State from Storage如何从存储中更新 React Native 功能组件状态
【发布时间】:2021-12-24 05:51:14
【问题描述】:

我有这个组件正在尝试使用从存储中加载的对象来设置其状态:

import React from "react";
import { ReactElement } from "react-native/node_modules/@types/react";
import { useState } from "react";
import { Text, View } from "react-native";
import MyClass from "./MyClass";
import AsyncStorage from "@react-native-async-storage/async-storage";

export default function FunCompWithState(): ReactElement {
  const [myClass, setMyClass] = useState<MyClass>(new MyClass());

  const promised = loadFromStorage();

  // I've also try calling this in a useEffect()
  promised.then(c => setMyClass(c));

  return (
    <View>
      <Text>{myClass.getTitle()}</Text>
      <Text>{myClass.getValue()}</Text>
    </View>
  );
}

async function loadFromStorage(): Promise<MyClass | null> {
  const jsonValue = await AsyncStorage.getItem("@main.myClass");
  console.log(jsonValue);
  if (jsonValue != null) {
    return Promise.resolve(JSON.parse(jsonValue));
  }
  return Promise.resolve(null);
}

在我的测试中,这是我得到的:

import * as React from "react";
import { act, render } from "@testing-library/react-native";
import FunCompWithState from "../FunCompWithState";
import MyClass from "../MyClass";
import AsyncStorage from "@react-native-async-storage/async-storage";

async function setup() {
    const storedClass = new MyClass();
    storedClass.setTitle("Stored Class");
    storedClass.setValue(8);
    await AsyncStorage.setItem("@main.myClass", JSON.stringify(storedClass));
}

it("Render FunCompWithState", () => {
  act(() => {
      setup();
  });

  const { debug } = render(<FunCompWithState />);
  debug();
});

当我运行测试时,我放置在loadFromStorage 函数中的console.log(jsonValue) 输出正确的值:{"title":"Stored Class","value":8}。但是,渲染的组件似乎没有正确的值:

    <View>
      <Text>

      </Text>
      <Text>
        1
      </Text>
    </View>

我希望看到这个:

    <View>
      <Text>
        Stored Class
      </Text>
      <Text>
        8
      </Text>
    </View>

那么我怎样才能在渲染组件中获得正确的值呢?这是我更新组件状态的问题,还是我测试组件的问题?

【问题讨论】:

    标签: typescript react-native jestjs


    【解决方案1】:

    为什么要在这里使用promise? 看起来应该更复杂。如果您的 getAsyncItem 不为 null ,您就不能在函数中使用 setState 吗?

      async function loadFromStorage() {
        const jsonValue = await AsyncStorage.getItem("@main.myClass");
        console.log(jsonValue);
        if (jsonValue != null) {
          setMyClass(JSON.parse(jsonValue));
        }
      }
    

    【讨论】:

    • 嗯。我可以尝试这样的事情。事实上,我已经对我的代码进行了一些抽象,我实际上希望有一个调用AsyncStorage 的通用函数,并在多个组件中使用该通用函数,而不是在我的代码库中的多个位置调用AsyncStorage。但是,我可以将 setter 传递给我的函数,而不是从我的函数中检索对象。如果这是标准做法,我会试一试。
    • 这似乎对我不起作用。为什么它应该工作对我来说是有道理的,但不幸的是它不是。
    • 好吧,如果你有一个状态并且你想避免重复,你可以制作一个自定义钩子并从你的组件中调用它。
    • 是的,这基本上就是我正在做的。
    猜你喜欢
    • 2021-10-07
    • 1970-01-01
    • 2020-07-06
    • 2020-04-25
    • 2020-08-12
    • 2021-01-12
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多