简体   繁体   English

为 Typescript React Native 功能组件创建 Promise

[英]Promise Creation for Typescript React Native Functional Components

I've got a very simple function set up to (eventually) load data from AsyncStorage .我已经设置了一个非常简单的函数来(最终)从AsyncStorage加载数据。 Currently I'm not even using AsyncStorage, but I'm just trying to make sure I'm using Promises correctly.目前我还没有使用AsyncStorage,但我只是想确保我使用的Promises正确。 Here is my simple code to get such a Promise :这是我获得这样一个Promise简单代码:

Storage.ts : Storage.ts

export async function poll(key: string): Promise<any> {
  try {
    console.log("polling");
    return new Promise((resolve, reject) => {
      resolve("Promised value.");
    });
  } catch (e) {
    // TODO: Log something.
  }
}

Then I'm trying to retrieve the promise here in my functional component:然后我试图在我的功能组件中检索这里的承诺:

ExampleAsyncComponent.tsx : ExampleAsyncComponent.tsx

import React, { useEffect, useState } from "react";
import { ReactElement } from "react-native/node_modules/@types/react";
import { poll } from "./Storage";
import { Text, View } from "react-native";

export default function ExampleAsyncComponent(): ReactElement {
  const [value, setValue] = useState<any>(null);
  const [refreshCount, setRefreshCount] = useState<number>(0);

  const loadedValuePromise: Promise<any> = poll("some.key");
  const updateValue = async () => {
    loadedValuePromise.then((v) => {
      setRefreshCount(refreshCount + 1);
      console.log("then count: " + refreshCount);
      setValue(v);
    });
  };

  useEffect(() => {
      setInterval(() => {
        updateValue();
      }, 2000);
  });

  return (<View><Text>hello</Text></View>);
}

I've added some logs to the console to try and visualize/debug how all of this is working, but I'm getting a LOT more logs than I would've expected.我已经向控制台添加了一些日志,以尝试可视化/调试所有这些是如何工作的,但是我得到的日志比我预期的要多得多。 With the code above, I would've expected "polling" to be printed out once and then every couple of seconds I would see "then count: x" .使用上面的代码,我希望"polling"打印一次,然后每隔几秒钟我就会看到"then count: x" However, it looks like I'm starting up a bunch of promises (and in my mind, I think that means I'm starting up a bunch of threads).然而,看起来我正在启动一堆承诺(在我看来,我认为这意味着我正在启动一堆线程)。 The longer this application runs in the browser (where I'm debugging my React Native app) the crazier the output gets, but here's the output from my app running for just a few seconds:这个应用程序在浏览器中运行的时间越长(我正在调试我的 React Native 应用程序),输出就越疯狂,但这是我的应用程序运行几秒钟的输出:

在此处输入图片说明

So I guess I have a couple of questions.所以我想我有几个问题。 Is this to be expected?这是意料之中的吗? If so, should I be expiring my promises somehow (I haven't found any examples of that yet)?如果是这样,我是否应该以某种方式使我的承诺到期(我还没有找到任何例子)? If this isn't to be expected, what am I doing wrong?如果这不是预期的,我做错了什么?

Effects need a list of dependencies as their second param. Effects 需要一个依赖项列表作为它们的第二个参数。

  // Calling poll in the render loop is surely a mistake
  // const loadedValuePromise: Promise<any> = poll("some.key");

  const updateValue = async () => {
    poll("some.key").then((v) => {
      setRefreshCount(refreshCount + 1);
      console.log("then count: " + refreshCount);
      setValue(v);
    });
  };

  useEffect(() => {
      setInterval(() => {
        updateValue();
      }, 2000);
  // An effect with an empty list of dependencies will run once on mount
  // and then never again.
  }, []);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM